admin管理员组

文章数量:1401661

I'm writing a simple React app that queries an API, gets a JSON list of items, and creates individual buttons for each item. Upon pletion of the API call, I change the state of the application to the JSON object, which causes the render() method to render a list of buttons.

axios.get('http://api_url')
.then(response => {
  this.setState({applicationJSON: response.data});
})
.catch(function (error) {
  console.log(error);
});

The problem is, I cannot attach an onClick to these buttons.

renderItems(text) {
return (
  <div>
    {
      text.map(function(name, index) {
        return <Button text={text[index].name} onClick={() => handleClick()} />
      })
    }
  </div>
);
}

Whenever I click one of these buttons, I get an error that handleClick() is not defined.

I know this is a problem with dynamically generated elements, as when I create a Button item in the constructor and bind the onClick to handleClick, handleClick() gets called.

What is the correct way to handle button clicks for dynamically generated ponents in React?

I'm writing a simple React app that queries an API, gets a JSON list of items, and creates individual buttons for each item. Upon pletion of the API call, I change the state of the application to the JSON object, which causes the render() method to render a list of buttons.

axios.get('http://api_url')
.then(response => {
  this.setState({applicationJSON: response.data});
})
.catch(function (error) {
  console.log(error);
});

The problem is, I cannot attach an onClick to these buttons.

renderItems(text) {
return (
  <div>
    {
      text.map(function(name, index) {
        return <Button text={text[index].name} onClick={() => handleClick()} />
      })
    }
  </div>
);
}

Whenever I click one of these buttons, I get an error that handleClick() is not defined.

I know this is a problem with dynamically generated elements, as when I create a Button item in the constructor and bind the onClick to handleClick, handleClick() gets called.

What is the correct way to handle button clicks for dynamically generated ponents in React?

Share Improve this question asked Jun 22, 2017 at 22:13 Mark SianoMark Siano 231 gold badge1 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

The reason it does not work is because when we use the function keyword (in the text.map), then this inside the function doesn't refer to the same this as the enclosing scope. You can either maintain a reference to the enclosing scope, e.g.

renderItem(text) {
    const self = this;
        return (
            <div>
                {text.map(function(name, index) {
                    return <Button text={text[index].name} onClick={self.handleClick} />
                })}
            </div>
        );
    }

Alternatively, you can make the whole thing a bit cleaner with some ES6 language features. Your mapping function can be simplified as well.

class MyComponent extends React.Component {
    handleClick = (evt) => {
        // do something
    }

    renderItem = (text) => {
        return (
            <div>
                {text.map(item => (
                    <Button text={item.name} onClick={this.handleClick} />
                ))}
            </div>
        );
    }
}

This works because this inside lambda functions (the => functions) refers to the outer context of the function.

本文标签: javascriptReactonClick for dynamically generated componentsStack Overflow