首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么ES6 ComputedPropertyName不与此反应js代码?

为什么ES6 ComputedPropertyName不与此反应js代码?
EN

Stack Overflow用户
提问于 2019-09-13 14:54:33
回答 1查看 41关注 0票数 2

使用react 16.9.0

我试图理解为什么以下内容无法更新组件titlestate属性

代码语言:javascript
复制
this.setState({
  [formControlName]: event.target.value
});

但这确实是:

代码语言:javascript
复制
this.setState({
  title: event.target.value
});

考虑以下构成部分:

代码语言:javascript
复制
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的用法如下:

代码语言:javascript
复制
<BookForm book={this.props.book}/>

一本书可能是这样的:

代码语言:javascript
复制
{
  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/"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-13 14:58:36

控制台在耍你。问题在于:

代码语言:javascript
复制
const formControlName = event.target.attributes['name'];

它获取属性节点name属性,而不是它的。我想,当您记录它时,它会以一种看起来像是字符串的方式显示属性节点。 property是元素属性的NamedNodeMap。按名称对其进行索引将为您提供 instance。将Attr实例转换为string (在Chrome上对我来说)将导致字符串"[object Attr]",因此您可能要向状态对象添加一个具有该名称的属性。:-)

相反,只需使用反射属性,它为您提供字符串值:

代码语言:javascript
复制
const formControlName = event.target.name;

为了完整起见:您也可以使用event.target.getAttribute("name")event.target.attributes['name'].nodeValue,但简单而惯用的方法是使用反射属性。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57925935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档