React - 使用带 window.location.href 的条件渲染来更改背景图像

React - Using Conditional Rendering with window.location.href to change Background image

我目前正在尝试创建主页有背景图片而其他页面没有的页面。我正在尝试添加条件渲染来完成此操作。我的代码在下面,后面是我想放在上面的 App 组件,但是我的语法显然是错误的(React noobie)。

if window.location.href == "/" || "/home" ?
    background = url;
else:
    background = none;

这是我的 app.js(我在 MainNav 组件中使用 React-router):

class App extends Component {
    constructor(props) {
    super(props);


        render() {
            return (
    <div className="App">

      <div className="contentContainer">
        <div className="navMenu">
          <NavHeader/>
        </div>
        <div className="sideLeftNav">
          <SidebarLeft/>
        </div>
        <div className="content">
          <MainNav/>
        </div>
        <div className="sideRightNav">
          <SidebarRight/>
        </div>
        <div className="footer">
          <Footer/>
        </div>
      </div>

    </div>
            )
        }
    }
}

我想我已经让自己变得更难了,但我对 props 和 state 还很陌生,我无法通过阅读其他问题来弄明白。我只是想在我的初始状态 ("/") 和 {home} 组件上显示背景图像,而在其他组件上没有背景图像。有人可以帮忙吗?

实现此输出的方法很少。但是使用 window.location.href 并不好,因为您使用的是 react-router。 (这里 window.location.href 是一个浏览器变量,其中输出将是完整的 url 例如 http://ab.com/12/cd 并且必须解析才能获得实际的应用程序路由。)
改为使用 this.props.location 属性 或 react-router。如果在 constructorrender 函数中 need-be,则检查当前路线并设置背景。

render(){
   const { location } = this.props
   const imgSrc = null

   if(location.pathname == "/" || location.pathname == "/home"){
      imgSrc = "ab.com/cd.jpg"
   }

   return (
      { imgSrc && <div ..... > </div>}
   )
}

不过这是按照给出的建议代码。另一种可能的方法是在不检查 url 或路由的情况下将背景图像放置在那些相关组件中。作为某处的示例,react-router

中应该有 <Router> 的实例
<Router>
  <Route path="/" component={BasicComponent}
  <Route path="/home" component={HomeComponent}
  <Route path="/other" component={OtherComponent}
</Router>

BasicComponentHomeComponent 中,您可以在 render 函数中包含背景图像。这也是一种可行的方法。