第九节-非受控组件

139 阅读1分钟

表单不受控于 state 的,使用React中的ref 从DOM节点获取表单数据的组件

  • 通俗的来说通过 ref → 来控制表单,不用状态值来控制
class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleReset = this.handleReset.bind(this);

    this.usenameRef = React.createRef();
    this.passwordRef = React.createRef();
    this.genderRef = React.createRef();
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(this.usenameRef.current.value, this.passwordRef.current.value,this.genderRef.current.value)
  }

  handleReset(e) {//=>重置
    e.preventDefault();
    this.usenameRef.current.value = '';
    this.passwordRef.current.value = '';
    this.genderRef.current.value = "male";
  }

  render() {
    return (
      <form onSubmit={ this.handleSubmit }>
        <p>
          密码:<input type="text" ref={ this.usenameRef }/>
        </p>
        <p>
          密码: <input type="password" ref={ this.passwordRef }/>
        </p>
        <p>
          {/* 默认值 - 组件挂载的完毕后进行更新,不会导致组件的更新 */}
          <select
            defaultValue="male"
            ref={ this.genderRef }
          >
            <option value="male"></option>
            <option value="famale"></option>
          </select>
        </p>
        <p>
          <button type="submit">登录</button>
          <button onClick={ this.handleReset }>重置</button>
        </p>
      </form>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

image.png

上传组件只能使用 非受控组件来实现

因为它是只读的,受控组件上面必须有onChange事件

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

    this.fileRef = React.createRef();
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(this.fileRef.current.files[0]);
  }

  handleReset(e) {
    //=>重置
    e.preventDefault();
    this.fileRef.current.value = '';
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <p>
          <input type="file" ref={this.fileRef} />
        </p>
        <p>
          <button type="submit">登录</button>
          <button onClick={this.handleReset}>重置</button>
        </p>
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

image.png

怎么去选择受控组件和非受控组件

  • 根据场景去选择,尽量去选着受控组件,如果不行去考虑非受控