網頁

2021/7/22

React Controlled Component與Uncontrolled Component差別

React form表單中Controlled Component與Uncontrolled Component差別。


簡單說兩者的差異在於Component的資料是否被React控制。
Controlled Component的資料由React控制;
Uncontrolled Component的資料由DOM控制。

Component的資料是否被React控制是指DOM element資料是否由來自於Component的state,即DOM element的資料與Component的state是否一致。


Controlled Component

下面Form組件<input/>value是由Formstate.value管理,所以是Controlled Component。

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''}; // source of input value

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  // update input changed value to component's state
  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        {/* input value is from component's state value */}
        <input value={this.state.value} onChange={this.handleChange} />

        <input type="submit"/>
      </form>
    );
  }
}

Unontrolled Component

下面Form組件<input/>value來源是參考到DOM節點,而非Component的state,所以是Unontrolled Component。

class Form extends React.Component {
  constructor(props) {
    super(props)
    this.input = React.createRef() // create reference to DOM node
    
    this.handleChange = this.handleChange.bind(this)
  }

  handleSubmit(event) {
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        {/* input value is from DOM's value */}
        <input ref={this.input} />

        <input type="submit"/>
      </form>
    );
  }
}


沒有留言:

張貼留言