【问题标题】:Specify Required Props for a Component指定组件所需的道具
【发布时间】:2018-09-03 22:22:52
【问题描述】:

我想指定一个组件所需的道具,以便在使用该特定组件时,我知道需要向它提供哪些数据,我该怎么做?

例如 // 我的要求的基本要点

class ABC extends React.Component{

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


class ABC_Caller extends React.Component{

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

在上面的示例中,当使用组件 ABC 时,我想以某种方式知道 reqProp 是我必须提供给 ABC 的必需属性,否则它将崩溃。

我希望这个检查是编译时而不是运行时。

【问题讨论】:

标签: javascript reactjs react-native babeljs


【解决方案1】:

你可以使用PropTypes:

import PropTypes from 'prop-types';

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

请注意,您同时指定了 string 类型并且它是必需的 (isRequired)。


如果你想编译时出错,你可以使用支持Flow的IDE(或者运行cli)。

Using Flow, you can declare the Props,并用?标记那些不需要的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多