在ReactJS中什么是受控组件和非受控组件?它们之间有什么不同?


当前回答

受控组件是React中做事的首选方式。

它允许我们将所有组件的状态保持在React状态,而不是依赖DOM通过其内部状态来检索元素的值。

受控组件是从状态中派生其输入值的组件。

其他回答

受控制的组件不保持它们的状态。

它们需要的数据从父组件传递给它们。

它们通过回调函数与这些数据交互,回调函数也从父进程传递给子进程。

这与有状态DOM组件(表单元素)有关,React文档解释了其中的区别:

A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component". A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

大多数原生React表单组件同时支持受控和不受控使用:

// Controlled:
<input type="text" value={value} onChange={handleChange} />

// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>

在大多数(或所有)情况下,您应该使用受控组件。

受控组件是React中做事的首选方式。

它允许我们将所有组件的状态保持在React状态,而不是依赖DOM通过其内部状态来检索元素的值。

受控组件是从状态中派生其输入值的组件。

受控组件是从回调函数获取更改值的组件 而且 未受控组件是拥有来自DOM的组件。 例如, 当输入值发生变化时,我们可以使用受控组件中的onChange函数 我们也可以使用像ref这样的DOM来获取值。

受控组件主要是那些组件的道具值来自父组件或来自存储的组件(如redux的情况)。例子:

<ControlledComp value={this.props.fromParent}/>

对于不受控制的组件,可以根据事件处理从组件的状态中获取组件值。例子:

<UncontrolledComp value={this.state.independentValue}/>