代码之家  ›  专栏  ›  技术社区  ›  gene b.

React:动态地将Img Src传递给子组件

  •  0
  • gene b.  · 技术社区  · 3 年前

    我有一个子组件,应该接收 icon=.. 属性动态加载图像。当静态指定为 img src={name} ,但在动态传递属性时,即使在父级和;孩子。

    import laptopHouse from './../images/icons/laptop-house.svg'
    
    export default function Infographic(props) {
        return (
    
    
            <Col lg={4} className="home-tile" id="my-telework-tile">
                <img src={props.icon} className="home-tile-img" alt=""/>
                <div className="home-tile-content">
                    <h2>{props.title}</h2>
                    <p>{props.text}</p>
                </div>
            </Col>
    
        );
    }
    

    用法

    import laptopHouse from './../images/icons/laptop-house.svg'
    
    export default function Home(props) {
        return (
             <Infographic icon="laptopHouse" title="Welcome" text="This is an infographic" />
        );
    }
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Prime    3 年前

    你应该通过” “在{大括号}

        2
  •  1
  •   kyun    3 年前

    我有一些解决办法。

    1. curly braces
    import laptopHouse from './../images/icons/laptop-house.svg'
    
    export default function Home(props) {
        return (
             <Infographic icon={laptopHouse} title="Welcome" text="This is an infographic" />
        );
    }
    
    
    1. 传递img本身
    export default function Infographic(props) {
        return (
            <Col lg={4} className="home-tile" id="my-telework-tile">
                {props.children}
                <div className="home-tile-content">
                    <h2>{props.title}</h2>
                    <p>{props.text}</p>
                </div>
            </Col>
    
        );
    }
    
    
    import laptopHouse from './../images/icons/laptop-house.svg'
    
    export default function Home(props) {
        return (
             <Infographic title="Welcome" text="This is an infographic">
               <img src={laptopHose} className="home-tile-img" alt=""/>
             </Infographic>
        );
    }