gpt4 book ai didi

javascript - 使用组件键从数组 Reactjs 中删除元素

转载 作者:行者123 更新时间:2023-12-02 13:45:18 25 4
gpt4 key购买 nike

所以我的代码可以工作,但我只是想澄清这是否是良好的编码实践,或者是否会在以后引起问题。

作为一点背景知识,这与我之前的问题 How to filter through array of components/elements in 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 });
}

child :

delete_this(value)
{
this.props.delete_this(value);
}
render()
{
<button onClick={this.delete_this.bind(this, this)} ref={ (input) => { this.button = input; } }>delete</button>
}

我尝试对对象本身进行过滤,但它不起作用,所以我改用了 key 。

最佳答案

正如您在另一个与此非常相似的问题中提到的,您不应该依赖像 _reactInternalInstance 这样的内部属性。

它们是“私有(private)的”,React 团队可以在技术上随时弃用它。我不知道 React 团队关于 semver 的政策,但我非常怀疑对内部 api 的更改是否算作重大更改。

所以回答你的问题,是的,它可能会导致问题。

您可以直接将 id 传递给删除方法:

<button onClick={() => this.props.delete_this(this.props.id)}>delete</button>

关于javascript - 使用组件键从数组 Reactjs 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41454234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com