组件声明

全面使用 ES6 class 声明,可不严格遵守该属性声明次序,但如有 propTypes 则必须写在顶部, lifecycle events 必须写到一起。

  • class
    • propTypes
    • defaultPropTypes
    • constructor
      • event handlers (如不使用类属性语法可在此声明)
    • lifecycle events
    • event handlers
    • getters
    • render
  1. class Person extends React.Component {
  2. static propTypes = {
  3. firstName: PropTypes.string.isRequired,
  4. lastName: PropTypes.string.isRequired
  5. }
  6. constructor (props) {
  7. super(props)
  8. this.state = { smiling: false }
  9. /* 若不能使用 babel-plugin-transform-class-properties
  10. this.handleClick = () => {
  11. this.setState({smiling: !this.state.smiling})
  12. }
  13. */
  14. }
  15. componentWillMount () {}
  16. componentDidMount () {}
  17. // ...
  18. handleClick = () => {
  19. this.setState({smiling: !this.state.smiling})
  20. }
  21. get fullName () {
  22. return this.props.firstName + this.props.lastName
  23. }
  24. render () {
  25. return (
  26. <div onClick={this.handleClick}>
  27. {this.fullName} {this.state.smiling ? 'is smiling.' : ''}
  28. </div>
  29. )
  30. }
  31. }