使用react 16.9.0。
我试图理解为什么以下内容无法更新组件title的state属性
this.setState({
[formControlName]: event.target.value
});但这确实是:
this.setState({
title: event.target.value
});考虑以下构成部分:
export class BookForm extends React.Component {
constructor(props) {
super(props);
this.state = { ...props.book };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const formControlName = event.target.attributes['name'];
// The following correctly logs "title"
console.log(formControlName);
// This does not work
this.setState({
[formControlName]: event.target.value
});
// This works, why?
this.setState({
title: event.target.value
});
}
handleSubmit(event) {
console.log('Form submitted...');
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label> Title:
<input type="text" name="title" value={this.state.title} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}BookForm的用法如下:
<BookForm book={this.props.book}/>一本书可能是这样的:
{
author: "Marijn Haverbeke"
description: "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."
isbn: "9781593275846"
pages: 472
published: "2014-12-14T00:00:00.000Z"
publisher: "No Starch Press"
subtitle: "A Modern Introduction to Programming"
title: "Eloquent JavaScript, Second Edition"
website: "http://eloquentjavascript.net/"
}发布于 2019-09-13 14:58:36
控制台在耍你。问题在于:
const formControlName = event.target.attributes['name'];它获取属性节点的name属性,而不是它的值。我想,当您记录它时,它会以一种看起来像是字符串的方式显示属性节点。 property是元素属性的NamedNodeMap。按名称对其进行索引将为您提供 instance。将Attr实例转换为string (在Chrome上对我来说)将导致字符串"[object Attr]",因此您可能要向状态对象添加一个具有该名称的属性。:-)
相反,只需使用反射属性,它为您提供字符串值:
const formControlName = event.target.name;为了完整起见:您也可以使用event.target.getAttribute("name")或event.target.attributes['name'].nodeValue,但简单而惯用的方法是使用反射属性。
https://stackoverflow.com/questions/57925935
复制相似问题