Học ReactJS Full Đầy Đủ Nhất

Bài 6: Props - Validation

Thuộc tính validation(xác thực) là một cách hữu ích để sử dụng đúng component. Việc này giúp ta trong quá trình phát triển sẽ tránh các lỗi và sự cố trong tương lai khi ứng dụng ngày càng bị Scale(Lớn ra, to ra). Validation còn giúp cho đoạn code trở nên dễ đọc hơn, vì ta có thể thấy được từng component nên được sử dụng như thế nào.
Các thành phần React đã sử dụng thuộc tính đặc biệt PropTypes giúp bạn bắt lỗi bằng cách xác thực các kiểu dữ liệu của các giá trị được chuyển qua các props, mặc dù không cần thiết phải xác định các thành phần với propTypes. Tuy nhiên, nếu bạn sử dụng propTypes với các component, nó sẽ giúp bạn tránh được các lỗi không mong muốn.

1 . Validating Props :

Mình sẽ tạo 1 App component với tất cả các Props mà mình cần. App.propTypes được sử dụng cho props validation(xác thực props). Nếu trường hợp một số props không sử dụng chính xác kiểu(type) mà mình đã chỉ định thì ta sẽ nhận được cảnh báo trên bảng điều khiển. Sau khi đã tạo các mẫu validaion, ta sẽ tiếp tục set App.defaultProps như sau :
App.jsx
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h3>Array: {this.props.propArray}</h3>
            <h3>Bool: {this.props.propBool ? "True..." : "False..."}</h3>
            <h3>Func: {this.props.propFunc(3)}</h3>
            <h3>Number: {this.props.propNumber}</h3>
            <h3>String: {this.props.propString}</h3>
            <h3>Object: {this.props.propObject.objectName1}</h3>
            <h3>Object: {this.props.propObject.objectName2}</h3>
            <h3>Object: {this.props.propObject.objectName3}</h3>
         </div>
      );
   }
}

App.propTypes = {
   propArray: React.PropTypes.array.isRequired,
   propBool: React.PropTypes.bool.isRequired,
   propFunc: React.PropTypes.func,
   propNumber: React.PropTypes.number,
   propString: React.PropTypes.string,
   propObject: React.PropTypes.object
}

App.defaultProps = {
   propArray: [1,2,3,4,5],
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "String value...",
   
   propObject: {
      objectName1:"objectValue1",
      objectName2: "objectValue2",
      objectName3: "objectValue3"
   }
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));
Nhấn npm start trong terminal để chạy :
kết quả như sau :

Syntax :

class App extends React.Component {  
          render() {}  
}  
Component.propTypes = { /*Definition */};

Một số Props Validator :

3. Ví dụ :

Mình sẽ tạo một App component chứa tất cả các props cần thiết. Trong ví dụ này, App.propTypes được sử dụng xác thực props. Để làm được, bạn phải thêm dòng này: import PropTypes from 'prop-types' in App.js file.
import React, { Component } from 'react';  
import PropTypes from 'prop-types';  
class App extends React.Component {  
   render() {  
      return (  
          <div>  
              <h1>ReactJS Props validation example</h1>  
              <table>  
                  <tr>  
                      <th>Type</th>  
                      <th>Value</th>  
                      <th>Valid</th>  
                  </tr>  
                <tr>  
                      <td>Array</td>  
                      <td>{this.props.propArray}</td>  
                      <td>{this.props.propArray ? "true" : "False"}</td>  
                  </tr>  
                  <tr>  
                      <td>Boolean</td>  
                      <td>{this.props.propBool ? "true" : "False"}</td>  
                      <td>{this.props.propBool ? "true" : "False"}</td>  
                  </tr>  
                  <tr>  
                      <td>Function</td>  
                      <td>{this.props.propFunc(5)}</td>  
                      <td>{this.props.propFunc(5) ? "true" : "False"}</td>  
                  </tr>  
                  <tr>  
                      <td>String</td>  
                      <td>{this.props.propString}</td>  
                      <td>{this.props.propString ? "true" : "False"}</td>  
                  </tr>  
                  <tr>  
                      <td>Number</td>  
                      <td>{this.props.propNumber}</td>  
                      <td>{this.props.propNumber ? "true" : "False"}</td>  
                  </tr>  
             </table>  
        </div>  
        );  
   }  
}  
App.propTypes = {  
    propArray: PropTypes.array.isRequired,  
    propBool: PropTypes.bool.isRequired,  
    propFunc: PropTypes.func,  
    propNumber: PropTypes.number,  
    propString: PropTypes.string,   
}  
App.defaultProps = {  
    propArray: [1,2,3,4,5],  
    propBool: true,  
    propFunc: function(x){return x+5},  
    propNumber: 1,  
    propString: "JavaTpoint",  
}  
export default App;
Main.js
import React from 'react';  
import ReactDOM from 'react-dom';  
import App from './App.js';  
  
ReactDOM.render(<App/>, document.getElementById('app'));
npm start ở terminal và ta sẽ được kết quả như sau :

4 . Tùy chỉnh validation :

ReactJS cho phép tạo một hàm tùy chỉnh validation gồm các phần :
  • props : Đối số đầu tiên
  • propName : Tên propName dùng để xác thực
  • componentName :  componentName sẽ được xác thực lại