gpt4 book ai didi

javascript - React.js 中 ES5 和 ES6 构造函数的区别

转载 作者:行者123 更新时间:2023-11-30 14:21:27 25 4
gpt4 key购买 nike

在 React 的源代码中,原型(prototype)函数有一个带有三个参数的签名:

函数组件( Prop ,上下文,更新程序){

但每次我看到有人使用现代 ES6 功能扩展 React.Component 时,他们声明的构造函数仅包含 props 如下:

构造函数(props)

原型(prototype)函数和 constructor 字面量有什么区别?剩下的两个参数去哪儿了?

最佳答案

您显然可以使用组件中提供的所有三个参数。但一般来说,只有在高级情况下我们才会使用 props,而不是每次都使用。同样,您可以使用其他人。

这是一个 context 的例子接口(interface):

ES6 类组件

class ContextConsumer extends React.Component {
/*
contexTypes is a required static property to declare
what you want from the context
*/
static contextTypes = {
currentUser: React.PropTypes.object
};
render() {
const {currentUser} = this.context;
return <div>{currentUser.name}</div>;
}
}

具有重写构造函数的 ES6 类组件

class ContextConsumer extends React.Component {
static contextTypes = {
currentUser: React.PropTypes.object
};
constructor(props, context) {
super(props, context);
...
}
render() {
const {currentUser} = this.context;
return <div>{currentUser.name}</div>;
}
}

示例取自 this blog .我会建议您查看博客以更加熟悉它。

另一个参数是 updater,您可能已经使用了 this.forceUpdate() 并且这样做会调用更新程序。但事实上,我们在正常情况下并不直接使用updater。不过,我还没有遇到过在构造函数中使用更新程序的情况。如果您面临一些高级案例,您也许能够弄清楚。


坦率地说,为了巧妙地使用 react,我什至从未尝试尽可能地使用 props。它们只是为我们提供的,以便我们可以在需要时在生命周期 Hook 中使用。


好吧,让我用 React 代码稍微解释一下:

function Component(props, context, updater) {
this.props = props;
this.context = context;
// If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.forceUpdate = function(callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

Component 函数有 3 个在函数内部使用的参数。稍后,它的原型(prototype) forceUpdate 被定义,updater 被 Hook 以使用 enqueueForceUpdate 将 forceUpdate 入队。所以,this.forceUpdate 实际上调用了 Component 更新器并允许我们重新渲染组件。我希望现在查看它的原型(prototype)方法是有意义的。


What is the difference between a prototype function and constructor literal?

据我了解,您想知道为什么使用所需的参数调用构造函数。

使用类/函数构造函数,以便您可以使用对函数的覆盖。例如,在构造函数中传递 props,你想用它来覆盖。因此,您明确通知函数使用构造函数中使用的 props。

关于javascript - React.js 中 ES5 和 ES6 构造函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52681151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com