【问题标题】:How does the state of React work?React 的状态是如何工作的?
【发布时间】:2017-10-11 11:51:33
【问题描述】:

我的代码在这里:https://jsfiddle.net/woyuditan26/bgwrfLxh/

      this.setState((prevState) => ({
        tasks: prevState.tasks.concat(newTask),
        text: ''  ////  why the input text is not cleared when I clicked the button ?
      }));

为什么我点击按钮时输入的文字没有被清除?

【问题讨论】:

  • 你在哪里使用text?
  • 我们是否有“debug-my-code”标签或类似标签?
  • 我建议你阅读这个react/docs/forms。
  • 因为您的表单是“不受控制的”:)

标签: reactjs state


【解决方案1】:

原因是,您使用的是uncontrolled element(因为您没有使用 input 元素定义 value 属性),要使其成为 controlled element 您需要使用 input 元素指定 value 属性。

像这样:

<input type="text" value={this.props.text} onChange={this.handleTextChange}/>

检查工作的fiddle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 2017-06-08
    • 2017-11-21
    • 2017-02-03
    • 2010-09-17
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多