Reactjs 如果元素类型为proptype,那么默认值是什么?

Reactjs 如果元素类型为proptype,那么默认值是什么?,reactjs,react-proptypes,Reactjs,React Proptypes,如果我尝试将proptype设置为PropTypes.element,而不是必需的,那么正确的默认设置是什么 static propTypes = { expandable: PropTypes.bool, popover: PropTypes.element, } static defaultProps = { expandable: false, popover: () => {}, } 谢谢默认值可以是: React.createEle

如果我尝试将proptype设置为
PropTypes.element
,而不是必需的,那么正确的默认设置是什么

static propTypes = {
    expandable: PropTypes.bool,
    popover: PropTypes.element,
  }

  static defaultProps = {
    expandable: false,
    popover: () => {},
  }

谢谢

默认值可以是:

React.createElement('div')

我认为
未定义的
应该有效

static defaultProps = {
  expandable: false,
  popover: undefined,
}

React中正确的默认组件或不存在的组件是
null
。您可以在
render()中使用它,如下所示:

render() {
    return (
        <div>{this.props.popover ? this.props.popover : null}</div>
    );
}

它是
React.createElement('div')
。在这里猜猜看!是的,成功了。我尝试了
React.createElement()
,但忘记了它需要一个实际的元素标记。回答这个问题,我会同意你为什么会有额外的元素?如果是可选的,则不需要默认设置。只需使用条件呈现
{this.props.popover | | null}
-同样适用于布尔值
if(this.props.expandable){}
->
->truthyWell,当您使用Airbnb的linting时,如果您将一个proptype定义为非必需,它将强制您使用默认值。在某种程度上是有意义的。注意,这个解决方案会用一个不需要的元素“污染”dom,这可能会导致布局问题(例如在css网格中)、间距问题(当使用计算元素的选择器时),或者只是在不应该有任何不需要的空间的地方添加不需要的空间。
static defaultProps = {
    expandable: false,
    popover: null,
}