Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

受控组件和非受控组件的区别 #61

Open
yuanyinghao1 opened this issue Jul 6, 2021 · 1 comment
Open

受控组件和非受控组件的区别 #61

yuanyinghao1 opened this issue Jul 6, 2021 · 1 comment

Comments

@yuanyinghao1
Copy link

No description provided.

@yixiaosi1314
Copy link

受控组件

1、每当表单的状态发生变化时,都会被写入到组件的state中
2、在受控组件中,组件渲染出的状态与它的value或checked prop相对应
3、react受控组件更新state的流程

<1> 通过在初始state中设置表单的默认值
<2> 每当表单的值发生变化时,调用onChange事件处理器
<3> 事件处理器通过合成对象e拿到改变后的状态,并更新应用的state
<4> SetState触发视图的重新渲染,完成表单组件值的更新

4、使用受控组件需要为每一个组件绑定一个change事件,并且定义一个事件处理器来同步表单值和组件的状态,某些情况可以使用一个事件处理器来处理多个表单域

5、在受控组件上指定 value 的 prop 可以防止用户更改输入。(如果指定了 value,但输入仍可编辑,则可能是意外地将value 设置为 undefined 或 null)

class ControlledForm extends Component {
  state = {
    username: ''
  }
  updateUsername = (e) => {
    this.setState({
      username: e.target.value,
    })
  }
  handleSubmit = () => {}
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          value={this.state.username}
          onChange={this.updateUsername} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

非受控组件

1、如果一个表单组件没有value prop就可以称为非受控组件
2、非受控组件是一种反模式,它的值不受组件自身的state或props控制
3、通常需要为其添加ref prop来访问渲染后的底层DOM元素

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants