javascript - React - onClick for dynamically generated components - Stack Overflow

I'm writing a simple React app that queries an API, gets a JSON list of items, and creates individ

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744264491a4565799.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信