Câu hỏi

Trong React uncontrolled component là gì?

Câu trả lời

Uncontrolled component trong React là một mẫu component mà trạng thái của nó không được quản lý bởi React. Trong uncontrolled components, dữ liệu form như giá trị của một input được xử lý bởi DOM thay vì bởi state trong component. Điều này có nghĩa là bạn sử dụng DOM như là "nguồn sự thật" để lấy giá trị hiện tại của input, thay vì lưu trữ giá trị đó trong state.

Cách Sử Dụng Uncontrolled Components

Để tạo một uncontrolled component, bạn thường sử dụng ref để truy cập trực tiếp đến phần tử DOM, thay vì sử dụng stateprops để kiểm soát các sự kiện như onChange. ref được sử dụng để lấy giá trị từ form khi cần thiết, chẳng hạn như khi form được gửi đi.

Ví dụ:

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleSubmit = (event) => {
    alert('A name was submitted: ' + this.inputRef.current.value);
    event.preventDefault();
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <inpu...
Bạn cần đăng nhập để xem
middle

middle

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

senior

Làm thế nào để force một component re-render với Hooks trong React?

Xem chi tiết
senior

Trong React, tại sao cần liên kết các event handler với this?

Xem chi tiết
middle

Cách sử dụng React.memo() như thế nào?

Xem chi tiết

Bình luận

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

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