0

I'm using React.js and I'm creating a todo app.

The contents are roughly like this code.

class TodoValue extends React.Component{

  _onChange(){
    console.log("atacked");
  }

  render(){
    return(
        <List>
          {
            this.props.todos.map(function(todo, i){
              return <ListItem key={i} primaryText={todo.item} rightIcon={<ActionInfo />} leftCheckbox={<Checkbox onClick={this._onChange.bind(this)} />} />
            })
          }
        </List>
    );
  }
}

Why can not I find the onChange function in checkbox?

Input and button to update information are omitted.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257

2 Answers2

0

Add a declaration into your constructor:

class TodoValue extends React.Component{
  constructor() {
    super()
    this._onChange = this._onChange.bind(this)
  }
  _onChange(){
    console.log("atacked");
  }

  render(){
    return(
        <List>
          {
            this.props.todos.map(function(todo, i){
              return <ListItem key={i} primaryText={todo.item} rightIcon={<ActionInfo />} leftCheckbox={<Checkbox onClick={this._onChange.bind(this)} />} />
            })
          }
        </List>
    );
  }
}

Notice the added constructor.

You can take a look here for a deeper explanation.

An Nguyen
  • 1,487
  • 10
  • 21
0

One option would be to use an es6 arrow function

Checkbox onClick={()=> this._onChange.bind(this)}

Another approach would be to utilise React's built in constructor method. Here you should bind the _onChange method to the component.

constructor(props) {
    super();
    this._onChange = this._onChange.bind(this)
  }

Then you can use

Checkbox onClick={this._onChange}
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54