Uncontrolled elements — such as text inputs, checkboxes, radio buttons, and entire forms with inputs — can always be uncontrolled or controlled.

    1. import React from 'react';
    2. const App = () => (
    3. <div>
    4. <label>
    5. My uncontrolled Input: <input type="text" />
    6. </label>
    7. </div>
    8. );
    9. export default App;

    上面这段代码,我们没有对input进行value和onChange变化的管理,input通过内部机制管理自己的状态

    在线运行:https://stackblitz.com/edit/react-syr4se

    1. import React, { useState } from 'react';
    2. const App = () => {
    3. const [value, setValue] = useState('');
    4. // const [value, setValue] = useState("Uncontrolled component");
    5. const handleChange = event => setValue(event.target.value);
    6. return (
    7. <div>
    8. <label>
    9. My still uncontrolled Input:
    10. <input type="text" onChange={handleChange} />
    11. </label>
    12. <p>
    13. <strong>Output:</strong> {value}
    14. </p>
    15. </div>
    16. );
    17. };
    18. export default App;

    以上是一个非受控组件,input区域是通过内部机制获取到的value,而output是通过state获取的value

    • input field receives its value from internal DOM node state
    • output paragraph receives its value from React’s state


    非受控组件可能会带来意想不到的bug,很多时候我们希望通过一个数据来源控制UI,通常是相同的props,state渲染相同的输出_: (props, state) => view.

    我们可以通过给input设置value的属性,从而将非受控转化为受控组件,从而统一UI的数据来源
    在线运行:https://stackblitz.com/edit/react-p4munb

    1. import React from "react";
    2. import "./style.css";
    3. import React, { useState } from 'react';
    4. const App = () => {
    5. const [value, setValue] = useState('Hello React');
    6. const handleChange = event => setValue(event.target.value);
    7. return (
    8. <div>
    9. <label>
    10. My controlled Input:
    11. <input type="text" value={value} onChange={handleChange} />
    12. </label>
    13. <p>
    14. <strong>Output:</strong> {value}
    15. </p>
    16. </div>
    17. );
    18. };
    19. export default App;

    参考 https://www.robinwieruch.de/react-controlled-components
    _