如何过滤reactjs中的组件/元素数组 [英] How to filter through array of components/elements in reactjs

查看:676
本文介绍了如何过滤reactjs中的组件/元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以当点击它时,我可以通过该按钮获取该按钮。但是当我做一个过滤器时,它不会删除所说的按钮。

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():

constructor()
{   
    super();
    this.options = [ 1, 2, 3, 4, 5]; 
    this.temp_option = []; 
    this.delete_me = this.delete_me.bind(this);
    this.buttons = [<button key="0" onClick={this.delete_me}/>,<button key="1" onClick={this.delete_me}/>];
    this.state = { buttons: this.buttons };
}

然后我有这个功能:

delete_me(e)
{   
    console.log(e.target);
    this.buttons = this.buttons.filter((item) => item != e.target);
    console.log(this.buttons);
}

然而 this.buttons 仍然有两个元素。

However this.buttons still has two elements in it.

我想到了删除它的另一种方法,那就是使用'key',但我似乎找不到任何关于获取键值的方法。

I thought about another way to delete it and it was to use the 'key', but I can't seem to find anything about getting key value.

推荐答案

首先,您需要将绑定到回调范围功能。如果要访问用于从合成事件中呈现按钮的反应对象实例,您可以使用私有变量 _targetInst

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 : [<button key="0" onClick={this.delete_me}>0</button>,<button key="1" onClick={this.delete_me}>1</button>]
    };
  }

  delete_me(e){
    const buttons = this.state.buttons.filter((button) => button != e._targetInst._currentElement);
    this.setState({ buttons });
  }   

  render() {
    return <div>{this.state.buttons}</div>;
  }
};

ReactDOM.render(
  <Buttons />,
  document.getElementById('container')
);

但是,如 Chris 提到,你的方法与React模式不太一致,你应该避免访问私有方法或属性(通常以下划线命名)

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)

这篇关于如何过滤reactjs中的组件/元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆