组件声明
全面使用 ES6 class 声明,可不严格遵守该属性声明次序,但如有 propTypes 则必须写在顶部, lifecycle events 必须写到一起。
- class
- propTypes
- defaultPropTypes
- constructor
- event handlers (如不使用类属性语法可在此声明)
- lifecycle events
- event handlers
- getters
- render
class Person extends React.Component {
static propTypes = {
firstName: PropTypes.string.isRequired,
lastName: PropTypes.string.isRequired
}
constructor (props) {
super(props)
this.state = { smiling: false }
/* 若不能使用 babel-plugin-transform-class-properties
this.handleClick = () => {
this.setState({smiling: !this.state.smiling})
}
*/
}
componentWillMount () {}
componentDidMount () {}
// ...
handleClick = () => {
this.setState({smiling: !this.state.smiling})
}
get fullName () {
return this.props.firstName + this.props.lastName
}
render () {
return (
<div onClick={this.handleClick}>
{this.fullName} {this.state.smiling ? 'is smiling.' : ''}
</div>
)
}
}