繁体   English   中英

在 React 应用程序中以编程方式在 index.html 中为 BODY 设置类

[英]Setting class for BODY in index.html programmatically in React app

我有一个非常标准的React应用程序。

到目前为止,我已经在index.html中为我的<body>标签设置了一个类,它呈现了一个看起来像这样的漂亮背景:

<body class="bg-123">

现在,我想根据 URL 以编程方式为<body>标记设置类。

具体来说,如果当前 URL 是http OR https://{host}/public ,我想将类设置为

<body class="bg-public">

在我开发应用程序时,这应该在生产和本地工作。 所以 URL 可能是:

http://localhost:3000/public或实际生产 URL https://myapp.com/public

我很感激这方面的一些指示。 谢谢!

因此,要回答你的问题,你可以通过访问身体document.body ,并使用访问其类document.body.classList ,所以你可以用它来做些什么样document.body.classList.toggle("some-class") . 您可以使用window.location.href访问当前 url,或者在这种情况下使用location.pathname可能会更好。

但更好的答案是,这种脚本编写对于 React 来说是非常反模式的。 更多 React-y 解决方案类似于在您的主要组件上创建一个类,您可以根据状态更改该类。 就像是:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { backgroundClass: "bg-123" }
  }
  render() {
    return (
      <div className={this.state.backgroundClass}>...</div>
    );
  }
  // This would be whatever event happens in your app that should cause the background to change
  handleSomeEvent() {
    this.setState({
      backgroundClass: "bg-456",
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM