From bd04b6f8abd924b2db6e52a52aef760f88eaac7c Mon Sep 17 00:00:00 2001 From: kinyaying Date: Fri, 3 Nov 2017 19:05:20 +0800 Subject: [PATCH] Update typechecking-with-proptypes.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- content/docs/typechecking-with-proptypes.md | 29 ++++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index 50c0a1a3..6dc978a0 100644 --- a/content/docs/typechecking-with-proptypes.md +++ b/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 ( +
Hello, {this.props.name}
+ ) + } +} +``` + +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`.