Javascript React中未更新的输入元素
我正在构建一个非常基本的React应用程序,但在表单输入方面存在一些问题: 我国:Javascript React中未更新的输入元素,javascript,reactjs,Javascript,Reactjs,我正在构建一个非常基本的React应用程序,但在表单输入方面存在一些问题: 我国: class App extends Component { constructor(){ super(); this.state = { books: [], book:{ author:"", title: "" } } this.handleInputChange = this.handleInputChange.bind(this)
class App extends Component {
constructor(){
super();
this.state = {
books: [],
book:{
author:"",
title: ""
}
}
this.handleInputChange = this.handleInputChange.bind(this)
}
我的表格:
<form onSubmit={this.addBook}>
<input
name="author"
type="text"
placeholder="author"
value={this.state.book.author}
onChange={this.handleInputChange}
/><br/>
<input
name="title"
type="text"
placeholder="title"
value={this.state.book.title}
onChange={this.handleInputChange}
/><br/>
<input type="submit" />
<button>Update</button>
<button>Delete</button>
</form>
我仍然无法在输入字段中输入数字。当我尝试对一个值进行数字运算时,什么也没有发生,输入字段也没有正确更新。有什么建议吗?
谢谢标题/作者属性位于book对象中。看起来您只是在引用state.author或state.title,但您需要引用state.book.title或state.book.author。试试这个:
handleInputChange(event) {
this.setState({
book[event.target.name]: event.target.value
});
}
图书状态为state.book.title和state.book.author,因此需要在setState中指定要使用event.target.value更新的state.book对象 希望这能起到作用:
handleInputChange(event) {
this.setState({
book: {
...this.state.book,
[event.target.name]: event.target.value
},
});
}
更新嵌套书本对象的状态时,需要对其进行复制,但要将要更改的属性设置为新值。这就是省略号符号的作用
此处的更多信息:哪个部件不能正常工作
handleInputChange
或addBook
?handleInputChange
handleInputChange(event) {
this.setState({
book: {
...this.state.book,
[event.target.name]: event.target.value
},
});
}