Specify Required Props for a Component

时间:2018-03-25 19:44:34

标签: javascript reactjs react-native babeljs

I would like to specify the props that are required for a component so that when that particular component is used, I know what data needs to be supplied to it, how do i do that?

e.g. // basic gist of my requirement

class ABC extends React.Component{

  render(){
   return (<View>this.props.reqProp</View>)
  }
}


class ABC_Caller extends React.Component{

  render(){
   return ( <ABC reqProp={'testData'} /> )
  }
}

In the above example when using the component ABC I would like to somehow know that reqProp is a required prop which I must supply to ABC without which it will crash.

I would prefer this check to be compile time and not run time.

1 个答案:

答案 0 :(得分:2)

You can use PropTypes:

import PropTypes from 'prop-types';

class ABC extends React.Component{
  render(){
   return (<View>this.props.reqProp</View>)
  }
}
ABC.propTypes = {
  reqProp: PropTypes.string.isRequired
};

Notice you are both specifying the string type and that it is required (isRequired).


If you want compile-time errors, you can use an IDE that supports Flow (or run the cli).

Using Flow, you can declare the Props, and mark those not required with a ?:

type Props = {
  reqProp: string,
  notRequiredProp?: string
};
class ABC extends React.Component<Props> {  // notice <Props>
  render(){
    return (<View>this.props.reqProp</View>)
  }
}