【问题标题】:When making react components es6 syntax why is super initialised with props? [duplicate]在制作反应组件 es6 语法时,为什么用道具超级初始化? [复制]
【发布时间】:2016-05-13 14:46:34
【问题描述】:

我想我不太擅长 JavaScript。
这就是我看到反应组件初始化的方式。初始设置状态在构造函数中完成。
export class Counter extends React.Component { constructor(props) { super(props); this.state = {count: props.initialCount}; }

为什么总是有super(props)。这是必需的吗?打电话超级有必要吗?如果不调用 super 会怎样?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    只有当你想在类的构造函数中访问 this.props 时,你才需要在 super 中传递 props。

    class Base extends React.Component {
    
        constructor(props) {
            console.log('Base', props);
        }
    
        render() {
            return <div>Base {this.props.name}</div>;
        }
    
    }
    
    class Sub extends Base {
    
        constructor(props) {
            super({
                name: 'New name prop'
            });
            console.log('Sub', arguments);
        }
    
    }
    
    var sub = <Sub name="Gomic" />
    
    React.render(sub, document.getElementById('container'));
    

    默认情况下,不会在构造函数中分配道具。它们在 React.createElement 方法中分配。所以super(props) 应该只在超类的构造函数手动将props 分配给this.props 时调用。当您只是扩展 React.Component 时,调用 super(props) 方法不会对 props 执行任何操作。

    参考:

    https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors-when-declaring-components-using-es6-classes/2781/2

    【讨论】:

    • 哦,谢谢,这是有道理的。如果根本不调用 super() 会发生什么?
    • super 仅相当于 ES5 中的 getInitialState()
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2021-06-17
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多