react-bootstrap:清除元素值

Shi*_*shi 4 javascript reactjs react-bootstrap redux

我试图在onClick事件发生后清除我的输入字段。

我正在使用react-bootstrap库,虽然有getValue()方法,但没有setValue(value)方法。

我偶然发现了这个讨论

为了在提交后简单地清理表单,我不完全理解他们的建议。

毕竟,如果我使用简单的 HTML<input>而不是react-bootstrap我可以通过元素获取节点ref并将其值设置为空字符串或其他东西。

什么被认为是清理 react-bootstrap<Input />元素的反应方式?

Bra*_*don 5

将状态存储在你的 React 组件中,通过 props 设置元素值,通过事件回调获取元素值。下面是一个例子:

这是直接从他们的文档中获取的示例。我刚刚添加了一个clearInput()方法来向您展示您可以通过更新组件的状态来清除输入。这将触发重新渲染,这将导致输入值更新。

const ExampleInput = React.createClass({
  getInitialState() {
    return {
      value: ''
    };
  },

  validationState() {
    let length = this.state.value.length;
    if (length > 10) return 'success';
    else if (length > 5) return 'warning';
    else if (length > 0) return 'error';
  },

  handleChange() {
    // This could also be done using ReactLink:
    // http://facebook.github.io/react/docs/two-way-binding-helpers.html
    this.setState({
      value: this.refs.input.getValue()
    });
  },

  // Example of how you can clear the input by just updating your state
  clearInput() {
    this.setState({ value: "" });
  },

  render() {
    return (
      <Input
        type="text"
        value={this.state.value}
        placeholder="Enter text"
        label="Working example with validation"
        help="Validation is based on string length."
        bsStyle={this.validationState()}
        hasFeedback
        ref="input"
        groupClassName="group-class"
        labelClassName="label-class"
        onChange={this.handleChange} />
    );
  }
});
Run Code Online (Sandbox Code Playgroud)