如果我想在组件内部有一个函数prop是可选的,那么使用defaultProps
分配noop
函数是否更好?或者如果函数存在与否,我应该检查整个组件吗?
例如可选的onChange
功能 -
<Input />
在Input.js
内
if(this.props.onChange){
this.props.onChange(e)
}
V.S.
defaultProps = {
onChange: () => {}
}
道具是必需的或可选的,它们在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以获取更多信息。