[英]onClick Function running while Rendering Component
class MappedEmoji extends React.Component{
render(){
const data = this.props.emoji.map(emoji => {
return(
<span onClick={this.props.handleClick(emoji)} className="myEmoji">{emoji}</span>
)
});
return(
<div> {data}</div>
)
}
}
class StickersComponent extends React.Component{
constructor(props){
super(props);
this.state={
Emoji:["😀","😁","😂","🤣","😃","😄","😅","😆","😊","😋","😎","😍","😘","🥰","😗"],
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(emoji){
console.log(emoji);
}
render(){
return(
<div className="stickers555">
<div className="_emoji">
{
<MappedEmoji emoji={this.state.Emoji}
handleClick = {this.handleClick}/>
}
</div>
</div>
)
}
}
ReactDOM.render(<StickersComponent />, document.getElementById('App'))
above is a code rendering all Emoji's perfectly, but as onclick handler binds to onClick function its not binding or may have some other problem. 上面的代码完美地呈现了所有Emoji表情,但是当onclick处理程序绑定到onClick函数时,它没有绑定或可能有其他问题。 as click handler is bind , i am getting all emoji's in console while rendering.
由于单击处理程序是bind,渲染时我将在控制台中获取所有表情符号。
Try calling as a callback. 尝试作为回调进行调用。
<span onClick={() => this.props.handleClick(emoji)} className="myEmoji">
If you have to pass an argument to a function, and you don't want to invoke it immediately, you need to use callback. 如果必须将参数传递给函数,并且不想立即调用它,则需要使用回调。
onClick={ () => yourFunction(argument1) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.