Could not access event handler function this.state inside: ReactJS

How do I get the state of a React component in this component function. This object has no state objects. I am getting this.state undefined in the Board function removeComment

. Basically in the Board function removeComment

I want to remove a comment item at that index (passed as an argument).

class Board extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            comments:[
            "One",
            "Two",
            "Three",
            "four",
            "five"
        ]};
    };
    removeComment(index) {
        console.log('i was called',this.state);
    }
    render() {
        console.log(this.state);
        return (
            <div className="board">
                {
                    this.state.comments.map((text,i) => {
                        return (
                            <Comment  key ={i} index = {i} commentText={text} removeComment={this.removeComment}/>
                        )
                    })
                }
            </div>
        );
    }
}

class Comment extends React.Component {
  removeComment() {
    var index = this.props.index;
    this.props.removeComment(index);
  }
  render() {
    return(
      <div onClick={this.removeComment.bind(this)}>{this.props.commentText}</div>
    );
  }
}

      

+3


source to share


1 answer


Since you forgot to bind the method removeComment

in Board

, use this line:

removeComment={this.removeComment.bind(this)}

      



Use this in a component Board

:

<div className="board">
    {
        this.state.comments.map((text,i) => {
            return (
                <Comment  key ={i} index = {i} commentText={text} removeComment={this.removeComment.bind(this)}/>
            )
        })
    }
</div>

      

+3


source







All Articles