处理可选的功能道具 - defaultProps或check prop存在吗?

问题描述 投票:1回答:1

如果我想在组件内部有一个函数prop是可选的,那么使用defaultProps分配noop函数是否更好?或者如果函数存在与否,我应该检查整个组件吗?

例如可选的onChange功能 -

<Input />

Input.js

if(this.props.onChange){
   this.props.onChange(e)
}

V.S.

defaultProps = {
   onChange: () => {}
}
reactjs
1个回答
0
投票

道具是必需的或可选的,它们在prop types中定义。

例:

Input.PropTypes = {
  onChange: PropTypes.func, // optional
  onBlur: PropTypes.func.isRequired, // required
  exampleProps: 'my example'
}

您不需要在defaultProps中传递noop函数。如果您需要初始化道具,即使用户未在组件中提供,也会使用默认道具。在上面的例子中,如果用户不提供exampleProps,则会在Input组件中接收prop exampleProps,否则Input组件将从提供的exampleProps道具Input获取/设置exampleProps

例如:

<Input exampleProps={'my new props'} />

输入将exampleProps设置为my new props

<Input />

输入将exampleProps设置为my example


根据您的要求,您不需要设置noop函数,但是prop类型将其类型设置为函数func,如果传递不正确的类型,它将向您发出一条错误,指出警告消息。

<Input onChange={123} />
{/* will throw you an error */}

或者,您也可以阅读此post以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.