什么是 React 受控组件和不受控组件? [英] What are React controlled components and uncontrolled components?

查看:18
本文介绍了什么是 React 受控组件和不受控组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What are controlled components and uncontrolled components in ReactJS? How do they differ from each other?

推荐答案

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

This relates to stateful DOM components (form elements) and the React docs explain the difference:

  • 一个 受控组件 是一个取其当前值的组件通过 props 并通过 onChange 等回调通知更改.父组件通过处理回调和管理自己的状态并将新值作为道具传递给受控组件来控制"它.您也可以将其称为哑组件".
  • 不受控制的组件是一个在内部存储自己状态的组件,并且您使用 ref 查询 DOM 以在需要时找到它的当前值.这有点像传统的 HTML.
  • 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 表单组件都支持受控和不受控的使用:

Most native React form components support both controlled and uncontrolled usage:

// 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>

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

In most (or all) cases you should use controlled components.

这篇关于什么是 React 受控组件和不受控组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆