受控组件: 受控组件是React中的一种组件,其特点是输入框的值(value)由React状态(state)控制。也就是说,React中的状态变化会直接影响输入框的值。受控组件通过form的输入元素(input, select等)的value属性绑定到状态上,然后通过onChange事件来更新状态。也就是说,用户在输入框中的输入会触发onChange事件,然后更新React状态,进而重新渲染组件。
例如:
- class Controlled extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- inputValue: '',
- };
- }
-
- handleInputChange = (event) => {
- this.setState({
- inputValue: event.target.value,
- });
- };
-
- render() {
- return (
- <input
- type="text"
- value={this.state.inputValue}
- onChange={this.handleInputChange}
- />
- );
- }
- }
例如:
- class Uncontrolled extends React.Component {
- constructor(props) {
- super(props);
- }
-
- handleInputChange = (event) => {
- console.log(event.target.value); // 输出用户输入的值
- };
-
- render() {
- return (
- <input
- type="text"
- value={this.props.value} // 由外部传入的值控制输入框的值
- onChange={this.handleInputChange}
- />
- );
- }
- }
总结:受控和非受控是两种处理表单输入元素的方式,受控组件完全依赖于React的状态和事件系统,而非受控组件则更加自由,但也需要自行处理更多的事情。