React Props là gì? Code ví dụ Props trong React

React Props là gì? Code ví dụ Props trong React

React Props là gì?

React Props là các tham số truyền vào React Component. React Props được truyền vào Component thông qua các HTML attributes.

React Props giống như các tham số của 1 function JavaScript hay các thuộc tính trong HTML

React Props là dữ liệu chỉ đọc (read only)

Các giá trị của props không bị thay đổi, khi muốn thay đổi trạng thái của component thì người ta chỉ thay đổi state của component chứ props thì không thay đổi được.

Nhắc lại một chút về function làm thay đổi dữ liệu hay không thì ta có 2 loại là pure functionimpure function:

  • pure function là các hàm không làm thay đổi dữ liệu của các tham số truyền vào, ví dụ:
function sum(a, b) {
  return a + b;
}
  • impure function là các hàm làm cho các tham số đầu vào bị thay đổi, ví dụ:
function withdraw(account, amount) {
  account.total -= amount;
}

Với impure function thì chúng ta thường bắt gặp khi đầu vào là một con trỏ hoặc một object, với những hàm như này thì khó control và debug.

Với pure function thì đơn giản hơn, ta chỉ cần quan tâm đầu vào là gì và đầu ra là gì, không lo dữ liệu bị thay đổi.

Tất cả các hành đồng của component liên quan tới props đều là pure function

Code ví dụ React Props

Tạo file index.html

<html>
<head>
  <title>stackjava: ReactJS tutorial!</title>
  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
</head>
<body>
  <div id='root'></div>
  <script src="index.jsx" type="text/babel"></script>

</body>
</html>

Tạo file index.jsx

// Create a ES6 class component
class Message extends React.Component {
 
  render() {
    return (
      <div>
        <h3>{this.props.content}</h3>
      </div>
    );
  }
}
 
const rootElement = document.getElementById('root')
 
// Use the ReactDOM.render to show your component on the browser
ReactDOM.render(
    <Message content="ReactJS, demo props"/>, rootElement
)

Props giống như 1 tham số, chỉ nhận dữ liệu lúc component được tạo và không bị thay đổi.

Demo:

Chạy file index.html và index.jsx trên server http: (Xem lại: ví dụ react hello world)

React Props là gì? Code ví dụ Props trong React

 

 

Okay, Done!

References:

https://reactjs.org/docs/components-and-props.html

stackjava.com