ReactJS: How can I have a more modular use of prop types & shapes for objects?

前端 未结 2 724
慢半拍i
慢半拍i 2020-12-31 04:17

I like to explicitly specify all my prop types for every class.

React.createClass({
  propTypes: {
    optionalArray: React.PropTypes.array,
    optionalBool         


        
2条回答
  •  囚心锁ツ
    2020-12-31 04:55

    I had the same problem and just moved the values to a separate ES6 module. In your example:

    // File lib/PropTypeValues.js
    import { PropTypes } from 'react';
    
    export let MemoryPropTypes = PropTypes.shape({
      memoryID: PropTypes.number,
      content: PropTypes.string,
      date: PropTypes.object,
      dateStr: PropTypes.string,
      note: PropTypes.string
    }).isRequired
    

    Then in your client code:

    // MemoryForm.jsx
    import { MemoryPropTypes } from './lib/PropTypeValues'
    import React from 'react';
    
    class MemoryForm extends React.Component {
      static propTypes: {
        memory: MemoryPropTypes,
        // ...
      };
    }
    

    Hope this helps.

提交回复
热议问题