Câu hỏi phỏng vấn Reactjs
Câu hỏi

What are Controlled components in ReactJS?

Câu trả lời

Controlled components in ReactJS are a method of managing form data where the form data is controlled by the state of the component. This approach ensures that the React component explicitly controls all aspects of the form's data at any given time.

Understanding Controlled Components

In controlled components, the form data is handled by the state of the component. This means that every state mutation will have an associated handler function. This pattern makes it easy to modify or validate user input in real-time using event handlers.

How Controlled Components Work

  1. State Management: The form elements such as <input>, <textarea>, and <select> maintain their current values in the component's state. For instance, an <input> element for a user's name might have its value controlled by a state variable called name.

  2. Binding State with Form Element: The value of the form element is bound to a state variable. This binding ensures that the input’s value is always synchronized with the React state. For example:

    <input type="text" value={this.state.name} onChange={this.handleNameChange} />

    Here, value={this.state.name} binds the input with the state, and any change in the input updates the state through onChange={this.handleNameChange}.

  3. Event Handling: Changes to the input are handled by functions that update the state. The onChange handler updates the state so that the component re-renders with the new value. For example:

    handleNameChange(event) {
        this.setState({name: event.target.value});
    }

Benefits of Controlled Components

  • Consistency and Predictability: Since the form data is handled by the React component's state, it ensures consistency across the application. The state serves as the single source of truth.
  • Integration with Other UI Elements: Controlled components integrate smoothly with other UI controls like buttons or dropdowns, which might depend on the form state.
  • Validation and Conditional Logic: They allow for immediate and conditional v...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

When would you use useRef ?

middle

What is Components Composition in React?

junior

What are portals in React and when do we need them?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào