简体   繁体   中英

onClick Function running while Rendering Component

onCLick handler running while rendering component, is there any error in code?

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. as click handler is bind , i am getting all emoji's in console while rendering.

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) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM