【问题标题】:Higher Order Component (lit-html)高阶组件 (lit-html)
【发布时间】:2021-03-22 15:49:04
【问题描述】:

我正在开发一个带有 lit-HTMLhaunted 的 Web 组件库。 我需要创建一个 HOC,因为我想在将道具传递给我的组件之前更新它们。 我尝试了一些东西,效果很好。

const hoc = (WrappedComponent) => (props) => {
  // here I update my props with a custom hooks
  const newProps = useProps(props);
  return WrappedComponent(newProps);
};

但是现在,“this”在我的组件中是未定义的。 我尝试绑定“this”,但没有任何效果。 “this”仍未定义

如果有人已经尝试创建高阶组件?你能分享我一些例子吗,请

【问题讨论】:

  • WrappedComponent 是函数式组件还是类组件?

标签: javascript web-component lit-html high-order-component


【解决方案1】:

但是现在,“this”在我的组件中是未定义的。我尝试绑定“this”,但没有任何效果。 “this”仍未定义

this 的问题似乎是您在那里使用了箭头函数(或者可能在您作为参数传递给hocWrappedComponent 定义中)。你不能为箭头函数绑定this,它总是继承自父作用域。如果您想绑定this(显式或从调用范围),您需要转换为非箭头函数。不知道除了这个问题你是否还有其他问题,但这可能会让你前进。

这取决于您尝试使用this 的确切位置,以及您可能需要从箭头函数转换的位置,但这里有一个示例,说明您如何为共享的代码执行此操作。根据您是否需要在此处调用this,您可能仍然可以在其中一种或两种情况下使用箭头函数。

const hoc = function (WrappedComponent) {
  return function (props) {
    // here I update my props with a custom hooks
    const newProps = useProps(props);
    return WrappedComponent(newProps);
  };
};

你能分享一段你的 this 未定义的上下文中的代码吗?

欲了解更多信息,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#arrow_functions

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2016-10-17
    • 2019-04-01
    • 2018-02-06
    相关资源
    最近更新 更多