English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

ReactJS 道具验证

La convalida delle proprietà è un metodo efficace per garantire l'uso corretto dei componenti. Questo aiuta a evitare errori e problemi futuri durante lo sviluppo, una volta che l'applicazione diventa più grande. Inoltre, rende il codice più leggibile, poiché possiamo vedere come ogni componente dovrebbe essere utilizzato.

Convalida dei prop

In questo esempio, utilizziamo tutti i prop necessari per creare il componente App. App.propTypes viene utilizzato per la convalida dei prop. Se alcuni prop non vengono utilizzati con il tipo corretto assegnato, riceveremo un avviso sulla console. Dopo aver specificato il modello di convalida, imposteremo App.defaultProps.

App.jsx

import React from 'react';
class App extends React.Component {
   render() {
      return (
         <div>
            <h3>Array: {this.props.propArray}</h3>
            <h3>Booleano: {this.props.propBool ? "Verificato..." : "Falso..."}</h3>
            <h3>Funzione: {this.props.propFunc(3)}</h3>
            <h3>Numero: {this.props.propNumber}</h3>
            <h3>Stringa: {this.props.propString}</h3>
            <h3>Oggetto: {this.props.propObject.objectName1}</h3>
            <h3>Oggetto: {this.props.propObject.objectName2}</h3>
            <h3>Oggetto: {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'));