[英]Using component key to delete element from array Reactjs
因此我的代码可以工作,但是我只是想澄清一下这是一种好的编码实践,还是以后会引起问题。
作为背景知识,这与我之前的问题类似: 如何通过reactjs中的组件/元素数组进行过滤 。 但是这次,我不是过滤dom元素数组,而是过滤组件数组。 这是我的操作方式:
上级:
delete_this(index)
{
let key = index._reactInternalInstance._currentElement.key;
this.repeats = this.repeats.filter( (item) =>
{
return item.key !== key;
});
this.setState({ repeats: this.repeats });
}
儿童:
delete_this(value)
{
this.props.delete_this(value);
}
render()
{
<button onClick={this.delete_this.bind(this, this)} ref={ (input) => { this.button = input; } }>delete</button>
}
我尝试对对象本身进行过滤,但是它没有用,所以我改用了键。
正如您在另一个与此非常相似的问题中提到的那样,您不应依赖_reactInternalInstance
类的内部属性。
他们是“私有的”,React团队可以在技术上随时弃用它。 我不知道关于semver的React团队政策,但是我高度怀疑将内部api计数更改为重大更改。
因此,要回答您的问题,是的,这可能会引起问题。
您可以直接将id直接传递给delete方法:
<button onClick={() => this.props.delete_this(this.props.id)}>delete</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.