react 直接 this.xxx 而不是 this.state.xxx 是什么

平时初始化的时候我都是用的

constructor(props) {
  super(props);
  // 初始化
  this.state = {}
}

今天看到别人写的我没见过的,

constructor(props) {
  super(props);
  // ...
  this.stream = null;
  this.video = null;
  // ...
}

请问上面两种初始化有什么区别?

我印象中出现this.xxx 的时候,这个 xxx应该是一个方法(<Component onClick={this.doSth}/>)

他这里的 this.stream = null; 我可以直接拿来用吗?比如

修改 this.stream=100 或者

取值 if(this.stream === 100) //.. 这样的?

阅读 3.6k
1 个回答

第一个能看懂么,能看懂,你就按第一个理解就可以了.

// ***** 对象字面量 *****
var obj = {
  text: 'hello',
  log() {
    console.log(this.text)
  },
}
obj.log() // hello

// ***
var obj = {
  setText() {
    this.text = 'hello'
  },
  log() {
    console.log(this.text)
  },
}
obj.setText()
obj.log() // hello

// ***** 构造函数 *****
function Obj() {
  this.text = 'hello'
  this.log = function() {
    console.log(this.text)
  }
}
var obj = new Obj()
obj.log() // hello

// ***** 类 *****
class Obj {
  constructor() {
    this.text = 'hello'
  }
  log() {
    console.log(this.text)
  }
}
var obj = new Obj()
obj.log() // hello

// ***** React *****
export default class Demo extends Component {
  constructor() {
    this.text = 'hello'
  }
  render() {
    console.log(this.text) // hello
    return <div />
  }
}

下面这里的this.stream this.video可以不写,直接用.
只是为了提高代码的可读性,让阅读代码的人知道,在这个组件里面挂载了这几个属性.
如果组件里面有用到自定义的属性,这么写会很友好,提高代码的可读性,防止给阅读此代码的人(包括自己)莫名的惊喜.

constructor(props) {
  super(props);
  // ...
  this.stream = null;
  this.video = null;
  // ...
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题