无法从 <textarea> 更新 React.js 状态

Trouble updating React.js state from <textarea>

我有一个表格,其中包含用于编辑现有对象的预加载信息。当我在输入字段中编辑信息时,一切正常,但是当我尝试在文本区域中编辑内容时,文本变得无法输入。如果我将属性 'value' 更改为 'defaultValue' 文本区域中未显示的旧文本。我的组件代码:

class PostEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: this.props.match.params.id,
      post: []
    };
  }

  componentDidMount() {
    this.showPost(this.state.id);
  }

  showPost(id){
    fetch(`/api/v1/posts/${id}`, 
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
    }
    }).then((response) => {return response.json()})
    .then((data) => {this.setState({ post: data }) });
  }

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  }

  render () {
    const { name, content } = this.state.post;
    return (
      <div>
        <form className="form" onSubmit={this.onSubmit}>
          <input id="name" className="form-control" type="text" name="name" defaultValue={name} onChange={this.onChange} required />
          <textarea id="content"  className="form-control" name="content" rows="8" cols="40" defaultValue={content} onChange={this.onChange}></textarea>    
          <input type="submit" value="Save" className="btn btn-success" id="btn-submit" />
        </form>
      </div>
    );
  }
}

我哪里做错了,我怎样才能使文本区域正常工作?

如果您打算 namecontent 成为 this.state.post 中的属性,则更新 constructor 中的初始 this.state 至少更改从数组 [] 键入对象 {} 并将 onChange() 处理程序更新为目标 this.state.post。此外,您还需要在输入和文本区域上使用 value 属性,而不是 defaultValue:

class PostEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: this.props.match.params.id,
      post: {},
    };
  }

  componentDidMount() {
    this.showPost(this.state.id); // may consider using this.props.match.params.id instead here
  }

  showPost(id){
    fetch(`/api/v1/posts/${id}`, 
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
    }
    }).then((response) => {return response.json()})
    .then((data) => {this.setState({ post: data }) });
  }

  onChange = (e) => {
    this.setState({ post: { ...this.state.post, [e.target.name]: e.target.value } });
  }

  render () {
    const { name, content } = this.state.post;
    return (
      <div>
        <form className="form" onSubmit={this.onSubmit}>
          <input id="name" className="form-control" type="text" name="name" value={name} onChange={this.onChange} required />
          <textarea id="content"  className="form-control" name="content" rows="8" cols="40" value={content} onChange={this.onChange}></textarea>    
          <input type="submit" value="Save" className="btn btn-success" id="btn-submit" />
        </form>
      </div>
    );
  }
}

这是一个 example 的动作。

希望对您有所帮助!