How to filter through array of components/elements in reactjs

前端 未结 2 762
栀梦
栀梦 2020-12-12 05:48

So I can get the button through the event when it is clicked on. But when I do a filter, it does not remove the said button.

So I have my array in the constructor():

2条回答
  •  情话喂你
    2020-12-12 06:21

    First of all, you need to bind this to the scope of your callback function. If you want to access the react object instance used to render the button from the synthetic event, you can do so using the private variable _targetInst.

    class Buttons extends React.Component{
    
      constructor(props) {
        super(props);
        this.delete_me = this.delete_me.bind(this);
            this.state = {
            buttons : [,]
        };
      }
    
      delete_me(e){
        const buttons = this.state.buttons.filter((button) => button != e._targetInst._currentElement);
        this.setState({ buttons });
      }   
    
      render() {
        return 
    {this.state.buttons}
    ; } }; ReactDOM.render( , document.getElementById('container') );

    However, as Chris mentioned, your approach is not very much in line with the React patterns, and you should avoid accessing private methods or properties (usually named with an underscore)

提交回复
热议问题