Catalog
  1. 1. defaultProps 的作用:
  2. 2. 添加 defaultProps 的两种方法
  3. 3. 推荐阅读
如何给组件添加默认props

defaultProps 的作用:

  • defaultProps 可以为 Class 组件添加默认 props
  • 这一般用于 props 未赋值,但又不能为 null 的情况

添加 defaultProps 的两种方法

  1. 在类中声明静态属性 static defaultProps ,这种方法只有浏览器编译以后才会生效。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    static defaultProps = {
    age: 18
    }

    render(){
    return(
    <h1>Hello, {this.props.name}. and my age is {this.props.age}</h1>
    )
    }
  2. 在类外为类追加 defaultProps 属性,这种方式会一直生效。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class App extends Component {
    render() {
    return (
    <div>
    {this.props.name}
    </div>
    );
    }
    }
    App.defaultProps={
    name:"jack"
    }

推荐阅读

Author: Erealm
Link: http://erealmsoft.github.io/2019/09/24/react/react-add-default-props/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment