[英]Trying to make a simple ToDo list with React, how can I push an item to an array?
I'm trying to make a simple ToDo list with React. 我正在尝试使用React创建一个简单的ToDo列表。 How can I push an item to an array?
如何将项目推入数组? I'm trying to use ES6.
我正在尝试使用ES6。 I would like to click the button, and get the contents of the input field displayed in a list.
我想单击该按钮,并在列表中显示输入字段的内容。
import React, { Component } from 'react';
class Example extends Component {
constructor(props) {
super(props);
this.state = {
query: [],
item: ''
}
}
render() {
return(
<div>
<form>
<fieldset>
<legend>Example</legend>
<input
type="text"
onChange={e => {this.setState({item: e.target.value})}} />
<button
onClick={() => {this.setState({ query: [...this.state.query, this.state.item]})}}>Add Item to Array
</button>
</fieldset>
</form>
{
this.state.query.map((q, key) => {
return(
<li key={key}>{q}</li>
)
})
}
</div>
)
}
}
export default Example;
EDIT: 编辑:
In the console, I see that an item is added to the array, however then the page refreshes, and the array is empty again. 在控制台中,我看到一个项目已添加到阵列中,但是随后页面刷新,并且阵列再次为空。 Should I add event.preventDefault somewhere to the button?
我应该在按钮的某处添加event.preventDefault吗?
EDIT: 编辑:
Solved it by adding type="button" to button. 通过在按钮中添加type =“ button”来解决该问题。 Instead of using the default 'submit' type.
而不是使用默认的“提交”类型。 Now it doesn't refresh the page, and I can see items added to the array, and displayed as a list.
现在它不会刷新页面,并且我可以看到添加到数组中的项目并显示为列表。 I was just practising, so I know to store the data I would need a database etc. :)
我只是在练习,所以我知道要存储需要数据库的数据,等等:)
Solved it by adding type="button" to button. 通过在按钮中添加type =“ button”来解决该问题。 Instead of using the default 'submit' type.
而不是使用默认的“提交”类型。 Now it doesn't refresh the page, and I can see items added to the array, and displayed as a list.
现在它不会刷新页面,并且我可以看到添加到数组中的项目并显示为列表。 I was just practising, so I know to store the data I would need a database etc. :)
我只是在练习,所以我知道要存储需要数据库的数据,等等:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.