bhb*_*bhb 5 javascript reactjs
我有一个可选的 propType
static defaultProps = {
onSort: undefined, // undefined | () => {}
}
Run Code Online (Sandbox Code Playgroud)
如果未定义,我们将undefined在调用函数之前进行检查。
_handleSort = () => {
this.props.onSort && this.props.onSort()
}
Run Code Online (Sandbox Code Playgroud)
那么,我如何处理 type 的 propType Function | undefined。我应该在调用函数之前检查 undefined 还是定义默认函数() => {}
static propTypes = {
onSort: PropTypes.oneOfType([
PropTypes.func,
PropTypes.any
])
}
Run Code Online (Sandbox Code Playgroud)
然后检查是否onSort存在。
if (this.props.onSort) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
或者
propTypes像这样定义:
static propTypes = {
onSort: PropTypes.func
}
Run Code Online (Sandbox Code Playgroud)
然后有一个onSort像这样的默认值:
static defaultProps = {
onSort: () => null
}
Run Code Online (Sandbox Code Playgroud)
static defaultProps = {
onSort: PropTypes.func,
}
if(this.props.onSort){
//do something
}
Run Code Online (Sandbox Code Playgroud)
那这个呢?因此,您在调用/使用该属性之前检查该属性是正确的。
| 归档时间: |
|
| 查看次数: |
8135 次 |
| 最近记录: |