What are React controlled components and uncontrolled components?

前端 未结 3 890
暗喜
暗喜 2020-11-28 04:15

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

相关标签:
3条回答
  • 2020-11-28 04:34
    • Controlled components notify other components about changes using callbacks. For example: <Button onClick={() => console.log("clicked")}>Click</Button>.
    • Uncontrolled components dont notify other components about their changes and you can access component only using ref-s. Ref might be useful if you need to access real dom of HTML element
    0 讨论(0)
  • 2020-11-28 04:37

    Controlled component is component that get the changed value from the callback function and uncontrolled component is component that have the one from the DOM. For example, When input value is changed,we can use onChange function in Controlled Component and also we can get the value using DOM like ref.

    0 讨论(0)
  • 2020-11-28 04:42

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

    • 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.

    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.

    0 讨论(0)
提交回复
热议问题