无需重新渲染即可获取输入值

时间:2016-08-31 16:36:17

标签: reactjs

我有一个文本输入(用于搜索文本)和一个按钮(用于启动搜索)。从所有示例来看,为了使searchtext值在我的搜索单击处理程序中可用(触发Action),我必须让输入使用状态值并在onChange发生时更新状态。这导致重新渲染。当用户只是在输入中键入字符时,如何避免所有重新呈现?我只想要按下搜索按钮时的值。

1 个答案:

答案 0 :(得分:1)

Simple: implement shouldComponentUpdate for your component: https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

EDIT:

  • Don't link this.state to your input element's value (<input value={this.state} />), this makes the input an uncontrolled component
  • Instead just give it a ref: <input ref={input => {this.inputElement = input}} />
  • When the submit button is hit just get the input value via the ref:

    const inputValue = this.inputElement.value

相关问题