Skip to content

Latest commit

 

History

History
71 lines (66 loc) · 2.14 KB

11. 非受控组件.md

File metadata and controls

71 lines (66 loc) · 2.14 KB

Uncontrolled Components

通常情况下建议使用控件controlled component管理forms数据,在控件中表单数据受控于React component,也就是实时通过监控onChange时间修改state。相反的,Uncontrolled Components中表单数据受DOM自己控制

以下uncontrolled component示例,借助ref获取DOM值,避免了在input中写监听事件了

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={(input) => this.input = input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

这样代码会简洁,比较简单的表单使用这种形式会更快捷点,React文档对它的形容是It can also be slightly less code if you want to be quick and dirty.

Default Values

React渲染周期中value属性会覆盖DOM中的值,表单默认值通过设置相应state属性值展示

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  render() {
    return (
      <form>
        <label>
          Name:
          <input type="text" value={this.state.value} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

uncontrolled component如果想要设置默认值,用defaultValue 而不是value,测试时使用value,表单的数据将不能改变,也就是无法再输入了

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <label>
        Name:
        <input
          defaultValue="Bob"
          type="text"
          ref={(input) => this.input = input} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

<input type="checkbox"><input type="radio">支持defaultChecked,<select><textarea> 支持 defaultValue