shoutingwei / react-learning

take notes for redux learning
0 stars 0 forks source link

非受控组件 #8

Open shoutingwei opened 5 years ago

shoutingwei commented 5 years ago

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

在大多情况下,我么推荐使用受控组件来实现表单。在一个受控组件时中,表单数据受React组件所控制。另一方法就是使用非受控组件,表单数据由DOM元素本身来处理。

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

写一个非受控组件,你可以用ref来获取DOM中的值,而不需要使用事件处理来给state做任何更新。

For example, this code accepts a single name in an uncontrolled component: 比如,这段代码是个非受控组件接受了一个name作为输入参数:

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

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

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

Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.

因为一个非受控组件的数据源在DOM本身,在使用非受控组件时,将React和非React代码一起使用更方便。如果你像快速写代码也不管代码的杂乱,那么使用非受控的方式会代码会少一些。否则,你应该用受控组件。

If it’s still not clear which type of component you should use for a particular situation, you might find this article on controlled versus uncontrolled inputs to be helpful.

如果你不清楚用哪一种,你应该按照文章对比受控和非受控组件。

Default Values In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.

默认值 在React的render生命周期中,表单上的值会重写DOM上的value。用一个非受控组件,当你想给它指定初始值,并让后续的更新由非受控组件控制。那么你可以指定一个默认值属性。defaultValue="Bob"

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

Likewise, and support defaultChecked, and