首页 > 解决方案 > React 用法中的构造函数/超级/绑定它们指定了什么?

问题描述

我查找了 General JS 中constructorsuperbind

示例代码。

import React from 'react';

class Example extends React.Component {
  constructor(props){
    super(props);
    this.state = { mood: confused }   
    this.doNothing = this.doNothing.bind(this);
  }

  doNothing(){} //I really do nothing

  render(){
    <button onClick={this.doNothing}>I do nothing xD</button>
  }
}

这是我现在所理解的

  1. State是一个对象,为了在我需要使用的类中创建一个对象constructor

  2. 子类constructor将覆盖父类constructor,我不知道里面有什么,React.Component但我相信它很重要。我认为在 React Document 中也说过:

    类组件应始终使用 props 调用基本构造函数。

  3. super会帮我做继承,super是替代父母的constructor。如果我需要使用thisinconstructor我需要编写super并走得更远,我需要传递一个参数 dosuper(props)才能使用this.props
  4. bind将创建一个与对象绑定良好的新函数,确保在调用该函数时,它将直接指向正确的对象,因为由于某种原因,如果我不绑定它,我的按钮会像<button onClick={undefined.doNothing}>,因为一些类规则:/(可选参数也可以帮助我设置有趣的前置参数,但这不是让我烦恼的)

这是我不明白的

  1. 我传递的参数的含义,我看过一些例子,但它们并没有真正传递任何参数。(中props constructor(props) super(props)
  2. 整个绑定代码在我看来很奇怪,this.doNothing改成什么?this.this.doNothing? 它是如何工作的,为什么我的按钮知道在哪里可以找到它?

我知道这有点基本,但我确实尽了最大努力,如果有人能帮助我,我将不胜感激。

标签: javascriptreactjsecmascript-6frontend

解决方案


当您使用this关键字定义变量时,它属于 React 类的范围,因此您可以在整个 React 类的范围内使用。

我传递的参数的含义,我看过一些例子,但它们并没有真正传递任何参数。

就 bind 而言,.bind它将上下文作为参数并返回一个函数,该函数在执行时将引用 React 类的上下文。传递给 bind 的其余参数在调用时可供函数使用。

例如当你写

constructor(props){
    super(props);  
    this.doNothing = this.doNothing.bind(this);
  }

bind 返回的函数被分配给doNothing在类范围内定义的变量。如果您将其更改为

constructor(props){
    super(props);  
    this.someNewFunction = this.doNothing.bind(this);
}

你会像使用它一样

render(){
    <button onClick={this.someNewFunction}>I do nothing xD</button>
  }

推荐阅读