【问题标题】:why we use this.setState() insted of super.setState() in react component为什么我们在反应组件中使用 this.setState() insted of super.setState()
【发布时间】:2018-04-08 02:09:30
【问题描述】:

我是 react 新手,我注意到我们使用 this.setState() 而不是 super.setState() 请我需要清楚地解释为什么我们使用它来调用超类方法? 示例:

class Checkbox extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                checked: true
            }
            this.handleCheck = this.handleCheck.bind(this)
        }

        handleCheck() {
            this.setState({
                checked: !this.state.checked
            })
        }

        render() {
            var msg 
            if(this.state.checked) {
                msg = "checked"
            } else {
                msg = "not checked"
            }
            return (
                <div>
                    <input type="checkbox" 
                           onChange={this.handleCheck}
                           defaultChecked={this.state.checked}/>
                    <p>This box is {msg}</p>
                </div>
            )
        }
    }       

【问题讨论】:

  • 因为它继承了超类的方法。
  • 所以我们从 super 继承的所有东西都可以使用 this 来调用它们?
  • 只要您不通过在组件中实现该方法来覆盖它(这从来都不是问题,因为您只实现了您自己不应该直接调用的生命周期方法)。
  • 继承。你只需要在 React 类构造函数中使用 super 关键字就可以在构造函数中使用 this 关键字。您可以使用它来访问父类上的方法,但没有必要。

标签: javascript reactjs ecmascript-6


【解决方案1】:

这就是 JavaScript 继承的工作原理。 Checkbox 子类的实例原型继承自 React.Component 父类 this.setState === super.setState

super.method 只有在子类中被覆盖时才应该被引用,它通常出现在被覆盖的方法本身中:

method() {
  super.method(); // inherit the behaviour from parent class
  // do something else
}

否则super.method()的使用会被认为是语义错误,这表明开发人员没有意识到继承机制。如果稍后将覆盖某个方法,则它不会因此而被使用(尽管在setState 的情况下不太可能)。

super.method() 的使用还要求开发人员了解父类的实现。正如this answer 中所解释的,只有父原型方法而不是实例方法可用作super。如果父类有实例方法,

method = () => {...}

子类将继承它为this.method,但不会有super.method

【讨论】:

  • (这也是其他语言的继承方式)
猜你喜欢
  • 2016-07-11
  • 2018-06-02
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多