使用重组组件作为参考时失去功能 [英] losing functions when using recompose component as ref
问题描述
我有这个简单的组件
class App extends React.Component {
a = () => null
b = () => null
c = () => null
render() {
return (<div>hey123</div>)
}
}
这是我的第二个组件,引用了第一个组件
and this is my 2nd component with ref to the first one
class BApp extends React.Component {
setComponentRef = ref => {
console.log('ref', ref)
this.playerComponentRef = ref
}
render() {
return (
<div>
<App ref={this.setComponentRef} />
</div>)
}
}
在这种情况下,在console.log中,我将收到所有App组件的功能(a,b,c)
但是如果我要在App
组件上使用Recompose.withState
,我将不再收到它们.在这里查看示例
https://codepen.io/anon/pen/qYjpoE?editors=1111
in this case in the console.log I will receive all App component's functions (a, b, c)
but if I'll use Recompose.withState
on App
component I will not receive them anymore. see example here
https://codepen.io/anon/pen/qYjpoE?editors=1111
查看swtich的工作方式
to see the working way swtich
<ModifyedApp ref={this.setComponentRef} />
到
<App ref={this.setComponentRef} />
我在这里想念什么?为什么使用Recompose HOC删除了App
类组件内部函数?
what am I missing here ? why the use of Recompose HOC is removing the App
class component inner functions ?
谢谢.
推荐答案
您可以将函数providerRef
传递给组件,然后像这样向其提供App实例
You can pass a function providerRef
to your component and then provide the App instance to it like
class BApp extends React.Component {
setComponentRef = ref => {
console.log('ref', ref)
this.playerComponentRef = ref
}
render() {
return (
<div>
<App providerRef={this.setComponentRef} />
</div>)
}
}
class App extends React.Component {
a = () => null
b = () => null
c = () => null
componentDidMount() {
this.props.providerRef(this);
}
render() {
return (<div>hey123</div>)
}
}
在Recompose的情况下,它是一个HOC,因此ref将应用于HOC而不是内部组件,某些库提供了一个withRef
钩子以使用this.playerComponentRef.getWrappedInstance()
访问innerComponent ref,但是我不确定关于它在recompose
中的可用性.
In case of Recompose, its an HOC and hence the ref will be applied on the HOC and not the inner component, some libraries provide a withRef
hook to access the innerComponent ref using this.playerComponentRef.getWrappedInstance()
, however I am not sure about its availability in recompose
.
这篇关于使用重组组件作为参考时失去功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!