Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React:构造函数使用带 props 参数的目的是什么 #99

Open
leslie1943 opened this issue Dec 21, 2020 · 0 comments
Open

React:构造函数使用带 props 参数的目的是什么 #99

leslie1943 opened this issue Dec 21, 2020 · 0 comments

Comments

@leslie1943
Copy link
Owner

构造函数使用带 props 参数的目的是什么

  • 在调用super()方法之前,子类构造函数不能使用this引用.这同样适用于ES6子类.
  • props参数传递给super()的主要原因是为了在子构造函数中访问this.props.

带 props 参数

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    console.log(this.props) // prints { name: 'John', age: 12 }
  }
}

不带 props 参数

class MyComponent extends React.Component {
  constructor(props) {
    super()

    console.log(this.props) // prints undefined

    // but props parameter is still available
    console.log(props) // prints { name: 'John', age: 42 }
  }

  render() {
    // no difference outside constructor
    console.log(this.props) // prints { name: 'John', age: 42 }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant