受控组件和非受控组件

2023/8/11 React

# 非受控组件

It is common to call a component with some local state “uncontrolled”.

通常将具有某些本地状态的组件称为“不受控制”。组件内部state或值不受props控制的组件,由组件内部自己管理

就像input组件,如果不给组件传value值,那么组件就是非受控组件,input组件内由自己管理value,这时如果要想拿到value则只能通过ref等手段,手动获取。

function App() {
  const inputRef = React.useRef(null);

  const handleSubmit = () => {
    if (inputRef.current) {
      console.log(inputRef.current.value);
    }
  };
  return (
    <>
      <input ref={inputRef} type="text" name="name" />
      <button onClick={handleSubmit}>submit</button>
    </>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 受控组件

In contrast, you might say a component is “controlled” when the important information in it is driven by props rather than its own local state. This lets the parent component fully specify its behavior.

当组件中的重要信息由props而不是其自身的本地状态驱动时,就说组件是“受控的”。组件内部state或值完全受props控制的组件

就像input组件,可以通过props传一个value使得input变为受控组件,input组件内部状态(值)就由props控制

function App() {
  const [value, setValue] = React.useState("");
  const handleSubmit = () => {
    console.log(value);
  };
  return (
    <>
      <input
        value={value}
        type="text"
        name="name"
        onChange={(e) => setValue(e.target.value)}
      />
      <button onClick={handleSubmit}>submit</button>
    </>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 反模式

anti-pattern (opens new window)

以非受控组件的使用方式去调用受控组件就是一种反模式。

示例codesandbox (opens new window)

什么时候使用受控组件、什么时候使用非受控?

  1. 当组件内部值或状态和外部存在交互逻辑时,则需要将其作为受控组件进行使用。
  2. 当组件内部值或状态除了受自身交换控制、还受到外部影响时,可使用受控组件。
  3. 当组件内部值或状态只由自身交换控制,不受外部影响时,可使用非受控组件。

参考:

最近更新: 2023年12月21日 17:06:46