我是 React js 新手,我很困惑如何通过 onclick 事件从子组件向父组件发送数据。
父组件
...
onTurn(id){
console.log(id)//undefined
}
renderCardsList(){
const {cardsList} = this.props
return cardsList.get('cards').map(({id,front_image}) => {
return <Card
image={front_image}
onTurn={this.onTurn}
/>
})
}
...
子组件
const Card = (props) => {
return(
<div className="singleCard">
<div className="imageDiv">
<img src={props.image} alt="work" />
</div>
<div className="bottombar">
<span onClick={e => props.onTurn(props.id)} className="glyphicon glyphicon-refresh" />
<span className="glyphicon glyphicon-pencil" />
<span className="glyphicon glyphicon-pushpin" />
</div>
</div>
)
};
最佳答案
您的 onClick
需要 props
上的 id
属性:
onClick={e => props.onTurn(props.id)}
但是您没有提供:
return <Card
image={front_image}
onTurn={this.onTurn}
/>
很自然地,卡片的 render
中的 props.id
是未定义
。
如果您希望卡片在 props
上有一个 id
,则需要指定一个,例如:
return <Card
image={front_image}
onTurn={this.onTurn}
id={/*something*/}
/>
关于javascript - 通过 onclick 事件从子级向父级 React js 发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45081923/