[英]Wrap a recursive Component with a higher-order component
Let's say that I have a simple component, and I want to log when it mounts.假设我有一个简单的组件,我想在它挂载时记录。 I can do this with a HOC that takes my component, defines a
componentDidMount
function, and returns a new component.我可以使用一个 HOC 来执行此操作,该 HOC 采用我的组件,定义一个
componentDidMount
function,并返回一个新组件。 Then I can create a new component let MyLoggedComponent = withLog(MyComponent)
and use MyLoggedComponent
where I want.然后我可以创建一个新组件
let MyLoggedComponent = withLog(MyComponent)
并在我想要的地方使用MyLoggedComponent
。
But let's say I have a recursive component, that is somewhere in it's render function it calls itself again:但是假设我有一个递归组件,它在它的某个地方渲染 function 它再次调用自己:
class MyRecursiveComponent extends React.Component {
...
render() {
... <MyRecursiveComponent />
...
}
Now, when I wrap this component let MyLoggedComponent = withLog(MyRecursiveComponent)
, only the outer instance of MyRecursiveComponent
will be wrapped, and componentDidMount
function will only fire once.现在,当我包装这个组件
let MyLoggedComponent = withLog(MyRecursiveComponent)
时,只会包装MyRecursiveComponent
的外部实例,并且componentDidMount
function 只会触发一次。
How can I wrap a recursive component so that it effects all instances of it?如何包装递归组件以使其影响它的所有实例?
You can get wrapped component right in the MyRecursiveComponent
:您可以在
MyRecursiveComponent
中获得包装的组件:
class MyRecursiveComponent extends React.Component {
const MyRecursiveComponentWithLog = withLog(MyRecursiveComponent);
render() {
...
<MyRecursiveComponentWithLog />
...
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.