Browse Source

Update typechecking-with-proptypes.md

1、Declare the defaultProps alone. And it is obeying AirBNB's styleguide.
2、Someone is confused about is it OK to put propTypes and defaultProps as static props inside React class. And we can explain about this question.
main
kinyaying 7 years ago
committed by GitHub
parent
commit
bd04b6f8ab
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 29
      content/docs/typechecking-with-proptypes.md

29
content/docs/typechecking-with-proptypes.md

@ -147,7 +147,11 @@ MyComponent.propTypes = {
You can define default values for your `props` by assigning to the special `defaultProps` property:
```javascript
```
const defaultProps = {
name: 'Stranger'
};
class Greeting extends React.Component {
render() {
return (
@ -157,9 +161,7 @@ class Greeting extends React.Component {
}
// Specifies the default values for props:
Greeting.defaultProps = {
name: 'Stranger'
};
Greeting.defaultProps = defaultProps;
// Renders "Hello, Stranger":
ReactDOM.render(
@ -168,4 +170,23 @@ ReactDOM.render(
);
```
You can also put propTypes and defaultProps as static props inside React class.
```
class Greeting extends Component {
static defaultProps = {
name: 'stranger'
}
render() {
return (
<div>Hello, {this.props.name}</div>
)
}
}
```
It is considerably more convenient. But non-functional properties are not currently supported for ES2015 classes, you should install extra plugin to support this syntax. If you want to only use strictly ES2015, the former syntax is the better choice.
The `defaultProps` will be used to ensure that `this.props.name` will have a value if it was not specified by the parent component. The `propTypes` typechecking happens after `defaultProps` are resolved, so typechecking will also apply to the `defaultProps`.

Loading…
Cancel
Save