开发者社区 问答 正文

#React 什么是默认道具?

#React 什么是默认道具?

展开
收起
因为相信,所以看见。 2020-05-08 10:51:58 464 分享 版权
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    defaultProps定义为组件类的属性,以设置该类的默认道具。用于未定义的道具,但不用于空道具。例如,让我们为按钮组件创建颜色默认道具,

    class MyButton extends React.Component {
      // ...
    }
    
    MyButton.defaultProps = {
      color: 'red'
    };
    
    

    如果未提供props.color,则它将默认值设置为'red'。即,无论何时尝试访问颜色道具,它都会使用默认值

    render() {
       return <MyButton /> ; // props.color will be set to red
     }
    
    

    注意:如果您提供空值,则它仍为空值。

    2020-05-08 10:52:47
    赞同 展开评论
问答分类:
问答标签:
问答地址: