reactjs之使用 es6 类时,React 中的 "super()"和 "super(props)"有什么区别

mayingbao 阅读:101 2025-06-02 22:19:02 评论:0

什么时候将 props 传递给 super() 很重要,为什么?

class MyComponent extends React.Component { 
  constructor(props) { 
    super(); // or super(props) ? 
  } 
} 

请您参考如下方法:

只有一个原因需要将 props 传递给 super():

当你想在构造函数中访问this.props时。

传递:

class MyComponent extends React.Component {     
    constructor(props) { 
        super(props) 
 
        console.log(this.props) 
        // -> { icon: 'home', … } 
    } 
} 

未通过:

class MyComponent extends React.Component {     
    constructor(props) { 
        super() 
 
        console.log(this.props) 
        // -> undefined 
 
        // Props parameter is still available 
        console.log(props) 
        // -> { icon: 'home', … } 
    } 
 
    render() { 
        // No difference outside constructor 
        console.log(this.props) 
        // -> { icon: 'home', … } 
    } 
} 

请注意,将 props 传递或不传递给 super 对以后使用 this.props 没有影响constructor 之外。即 rendershouldComponentUpdate 或事件处理程序始终 可以访问它。

这在 Sophie Alpert 的一篇文章中有明确说明 answer类似的问题。


文档— State and Lifecycle, Adding Local State to a Class, point 2 —建议:

Class components should always call the base constructor with props.

但是,没有提供任何理由。我们可以推测它要么是因为子类化,要么是为了将来的兼容性。

(感谢@MattBrowne 提供的链接)


标签:React
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号