在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}/>
推荐文章
- 如何配置历史记录?
- React钩子:从回调中访问最新状态
- React-Native:应用程序未注册错误
- ReactJS和公共文件夹中的图像
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- React组件中使用TypeScript的默认属性值
- 反应钩子-正确的方式清除超时和间隔
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 为什么React 16中的Fragments比容器div更好?
- 如何在ReactJS中验证嵌套对象的PropTypes ?
- 如何在ReactJS中从“外部”访问组件方法?
- 'React'指的是一个UMD全局,但当前文件是一个模块