【问题标题】:How to dynamically update a background image based on routing in a React framework如何在 React 框架中根据路由动态更新背景图片
【发布时间】:2019-01-24 11:08:05
【问题描述】:

我正在尝试根据各种路由选项更新背景图像。但是根本不显示背景。

我已经尝试过内联样式并确保我引用了正确的目录。

原来css只是通过改变html背景来设置背景,但我不能让它动态化。

class App extends Component {
   constructor() {
    super();
    this.state = {
      'route': 'Home'
    }
  }

  onRouteChange = (route) => {
    this.setState({route: route});
  }

  render() {
    if (this.state.route === 'Home') {
      return (
        <div className='App home'>
          <div style={{display: 'flex', justifyContent: 'flex-end', backgroundColor: 'rgb(91,121,97, 0.5)'}}>
            <div style={{marginRight: 'auto'}}><Logo onRouteChange={this.onRouteChange}/></div>
            <Navigation onRouteChange={this.onRouteChange}/>
          </div>
            <SideBar/>
        </div>
      )
    } else {
      return(
        <div className='App theAnimalKingdom'>
         <div style={{display: 'flex', justifyContent: 'flex-end', backgroundColor: 'rgb(91,121,97, 0.5)'}}>
           <div style={{marginRight: 'auto'}}><Logo onRouteChange={this.onRouteChange}/></div>
           <Navigation onRouteChange={this.onRouteChange}/>
         </div>
        </div>
      )
    }
  }
}

export default App;

app.css 如下所示。

div.app {
    height: 100%;
    width: 100%;
}

div.home {  
    background-image: url('./Images/cover.jpg') no-repeat center bottom fixed;
    background-size: 100% 100%;
}

div.theAnimalKingdom {  
    background-image: url('./Images/other.jpg') no-repeat center bottom fixed;
    background-size: 100% 100%;
}

如果 this.status 应该变成 theAnimalKingdom 那么背景应该变成 other.jpg

【问题讨论】:

  • 那么问题是什么?除了不同的类名之外还有什么问题 - JSX 中的 Home 与 CSS 中的 .home
  • 好吧,我是新手,但我会尽力提供帮助,我会尝试为背景创建一个道具,你想将背景更改为完整视图吗?一个特定的元素?也许你可以改变道具就像你在开关reacttraining.com/react-router/core/api/Switch切换路线@
  • @Aprillion 谢谢,我确实把家改成了家,但问题仍然存在。我根本没有背景,只有一个带有附加元素的白页。
  • @DanielVafidis 谢谢,看起来很有帮助。我会试一试。它根本没有解决我没有背景的问题。路由工作得很好。我希望将背景更改为全视图。

标签: css reactjs routes


【解决方案1】:

对于background-image 的 CSS &lt;url&gt; 值,没有 ./something(“当前”文件夹的相对路径)之类的东西。

您可以使用相对 URL,但这些是相对于 CSS 文件的(在 webpack/typescript/... 编译后的 build 文件夹中 - 如果使用 create-react-app,则从 public 文件夹中复制资产全部,但来自src 的资产仅在实际导入时才使用)。

Setting a backgroundImage With React Inline Styles 可能更容易,但也可以将图像放到public 文件夹中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-02-16
    • 1970-01-01
    • 2015-10-04
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多