在React中使用this.props和props之间有区别吗?

ree*_*rix 10 reactjs

在你定义之后this,使用this.props和之间有区别props吗?

constructor(props) {
  super(props);

  this.state = {
    input: this.props.input,
    input2: props.input2
  };
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,inputinput2这里有什么区别?

Raf*_*fat 16

ES2015(ES6)课程的规则基本上归结为:

在子类的构造函数,不能被使用,直到被调用.

ES6类构造函数必须调用super,如果它们是子类,或者它们必须显式返回一些对象来取代未初始化的对象.

因此,在构造函数中调用super(props).道具和this.props是一样的.所以,

props === this.props // true
Run Code Online (Sandbox Code Playgroud)


Md.*_*med 5

基本上,在这种情况下是相同的,但是如果您考虑整个组件,则props只有在props作为函数参数传递时才可用,例如以下示例

componentWillMount(){
  this.someFunc(this.props);
}

componentWillReciveProps(nextProps){
  this.someFunc(nextProps);
}

someFunc(props) {
 ...... 
 // in here props and this.props are completely different
 as props is you latest props while this.props can be you previous props
}
Run Code Online (Sandbox Code Playgroud)

虽然您可以this.props从组件的任何位置进行访问,但我希望这能给您带来灵感