【问题标题】:Changing Background image using Create React App使用 Create React App 更改背景图像
【发布时间】:2021-12-01 19:22:29
【问题描述】:

在使用 Create React App 更改通过 props 提供给组件的背景图像时遇到问题。文档说使用导入语法。这可行,但这意味着我必须将每个背景图像硬编码到每个组件。无论如何要动态地做到这一点?

我注意到它也不允许我在导入语法中使用模板文字。我认为这会解决我的问题。

import '../css/Avatar.css';
import photo from "../images/joe_exotic.jpg";


const Avatar = (props) => {

    return (
        <div 
        style={{backgroundImage: `url("${photo}")`}}
        className="avatar">
        </div>
    )
}

export default Avatar;

P.S:我查看了 StackOverflow 上关于此的其他文章,但它们并没有提供太多帮助。

【问题讨论】:

    标签: javascript reactjs create-react-app


    【解决方案1】:

    如果你想避免这种方式,你可以把你的图片放在你的React 应用程序的public 文件夹中,然后像这样抓取它们:

    import '../css/Avatar.css';
    
    const Avatar = (props) => {
    
        return (
            <div 
            style={{backgroundImage: `url("/joe_exotic.jpg")`}}
            className="avatar">
            </div>
        )
    }
    
    export default Avatar;
    

    【讨论】:

      【解决方案2】:

      我希望它对你有用。祝你好运。

      import '../css/Avatar.css';
      import photo from "../images/joe_exotic.jpg";
      
      
       const Avatar = (props) => {
      
       return (
          <div 
          style={{backgroundImage:url(photo)}}
          className="avatar">
          </div>
      ) }
      export default Avatar;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 2021-06-17
        • 2011-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多