gpt4 book ai didi

javascript - 指定组件所需的 props

转载 作者:行者123 更新时间:2023-12-01 02:16:31 25 4
gpt4 key购买 nike

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

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

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 是必需的 prop,我必须将其提供给 ABC,否则它将崩溃。

我希望在编译时而不是运行时进行此检查。

最佳答案

您可以使用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>)
}
}

关于javascript - 指定组件所需的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com