通过道具

时间:2018-04-12 08:48:32

标签: javascript reactjs react-props

使用react,我的app.js中有一个简单的console.log('hello')。我通过道具将它传递给一个组件,“缩略图组”将映射到一个数组,创建“缩略图”,并且每一个都应该用onClick激活该方法。当我这样做时,没有任何反应。我错过了什么?

App.js

escolheTextura = () => {
    console.log('hello')
};


    <ThumbnailGroup

     escolheTextura={this.escolheTextura}/>

ThumbnailGroup.js

 return (
            <div className={["column", "group"].join(' ')}>
                {
                    props.texturas.map(thumbnail => {
                            return <Thumbnail
                                onClick={() => props.escolheTextura()}>
                                {thumbnail}
                            </Thumbnail>
                        }
                    )
                }
            </div>
    );

Thumbnail.js

    return (

        <div className={["button is-primary", "thumbnail"].join(' ')}>
            <span>
                <figure className={"image is-32x32"}>
                    <img src={"image is-32x32"}/>
                </figure>
            </span>
        </div>
    )
};

2 个答案:

答案 0 :(得分:1)

您应该进一步传递props.escolheTextura。 DOM元素接收点击,而不是React.js组件所以,你必须将你的函数传递给Thumbnail组件并制作一些DOM元素,说div来处理点击事件:

ThumbnailGroup.js

return (
        <div className={["column", "group"].join(' ')}>
            {
                props.texturas.map(thumbnail => {
                        return <Thumbnail
                            escolheTextura={props.escolheTextura}>
                            {thumbnail}
                        </Thumbnail>
                    }
                )
            }
        </div>
);

ThumbnailGroup.js

return (

    <div onClick={this.props.escolheTextura} className={["button is-primary", "thumbnail"].join(' ')}>
        <span>
            <figure className={"image is-32x32"}>
                <img src={"image is-32x32"}/>
            </figure>
        </span>
    </div>
)

答案 1 :(得分:1)

ThumbnailGroup.js

return (
         <div className={["column", "group"].join(' ')}>
         {
             props.texturas.map(thumbnail => {
                return <Thumbnail
                          escolheTextura ={props.escolheTextura}>
                          {thumbnail}
                       </Thumbnail>
              }
          }
            </div>
    );

Thumbnail.js

    return (
        <div onClick={props.escolheTextura} className={["button is-primary", "thumbnail"].join(' ')}>
            <span>
                <figure className={"image is-32x32"}>
                    <img src={"image is-32x32"}/>
                </figure>
            </span>
        </div>
    )
};