无法添加reactj中的项目列表
这已经有一段时间了,因为我使用了ReactJ,需要创建一个可以添加和删除的项目列表。我已经在我的LI上添加了一个onclick事件以删除它。我还有一个按钮可以添加新项目,这些项目似乎有效,但状态没有更新。
var new_items = [...Array(1)].map((val, i) => `No Items`);
<ul className="App-list">
{new_items.map((item, i) => (<li key={`item_${i}`} onItemClick={onItemClick(i)}>{ item }</li>))}
</ul>
onclick函数在这里,
function onItemClick(num) {
this.setState({
new_items: this.state.new_items.concat('new value')
})
}
我只需要从列表中删除一行,或者取决于状态,但即使它运行也不会更新状态。有人可以给我一个击球手,以动态更新行列表,或者告诉我我做错了什么。
Its been a while since I used ReactJS and I need to create a list of items that I can add to and remove. I've added an onClick event to my li to remove it. I also have a button to add new items, these seem to work but the state is not updating.
var new_items = [...Array(1)].map((val, i) => `No Items`);
<ul className="App-list">
{new_items.map((item, i) => (<li key={`item_${i}`} onItemClick={onItemClick(i)}>{ item }</li>))}
</ul>
the onClick function is here
function onItemClick(num) {
this.setState({
new_items: this.state.new_items.concat('new value')
})
}
I just need to either delete a line from the List or Add depending on status but even though it runs it does not update the state. Can someone give me either a batter way of updating a list of rows dynamically or tell me what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要添加一个构造函数如下:
然后调用ONCLICK函数时,您称其为以下方式:
另外,如果您使用的是通用
onClick
功能,则必须更改onItemClick 到
onclick
:由于您没有使用单击中的事件信息,因此必须添加一个匿名函数,该功能调用所需的
onclick
anderler。因此,()=&gt; this.onitemClick(i)
You need to add a constructor as follows:
Then while calling the onClick function you call it as follows:
Also, if you are using the generic
onClick
functionality, you would have to changeonItemClick
toonClick
:Since you are not using the event information from the click, you have to add an anonymous function that calls your desired
onClick
handler. Hence the()=>this.onItemClick(i)
由于您使用的是类组件,因此必须调用类的方法
Since you are using Class Component you have to call the method with the context of class