Reactjs - Props

04/01/2022   React

Reactjs - Props

Reactjs - Components

1. Props là gì

- Props là những tham số được chuyển vào component

- Props chuyển tham số vào component thông qua html antributes (thuộc tính)

- React Props giống tham số của hàm trong javascript và thuộc tính trong html

- Để chuyển props vào components sử dụng cấu trúc giống thuộc tính HTML

VD: chuyển props cho component

//có props là brand
const myelement = <Car brand="Ford" />;

// sử dụng props trong component

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand}!</h2>;
  }
}

2. Truyền Data

Props cho phép chuyển data từ component này đến component khác như tham số.

VD truyền tham số brand từ compoent Gagrage vào component Car

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand}!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my garage?</h1>
      <Car brand="Ford" />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));

- Nếu bạn có một biến để gửi chứ không phải một chuỗi như trong ví dụ trên, bạn chỉ cần đặt tên biến bên trong dấu ngoặc nhọn:

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand}!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    const carname = "Ford";
    return (
      <div>
      <h1>Who lives in my garage?</h1>
      <Car brand={carname} />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));

hoặc truyền một object

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.brand.model}!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    const carinfo = {name: "Ford", model: "Mustang"};
    return (
      <div>
      <h1>Who lives in my garage?</h1>
      <Car brand={carinfo} />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));

3. Sử dụng props trong hàm khởi tạo constructor 

Nếu component của bạn có một hàm khởi tạo constructor(), props phải luôn được chuyển cho hàm tạo và cả React.Component thông qua phương thức super (). nếu không truyền sẽ xảy ra lỗi.

class Car extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>I am a {this.props.model}!</h2>;
  }
}

ReactDOM.render(<Car model="Mustang"/>, document.getElementById('root'));

Lưu ý: React Props ở chế độ chỉ đọc! Bạn sẽ gặp lỗi nếu cố thay đổi giá trị của chúng.

Cám ơn

Bài viết cùng chủ đề