我有这个简单的组件
class App extends React.Component {
a = () => null
b = () => null
c = () => null
render() {
return (<div>hey123</div>)
}
}
这是我的第二个组件,引用了第一个组件
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
查看开关的工作方式
<ModifyedApp ref={this.setComponentRef} />
到
<App ref={this.setComponentRef} />
我在这里错过了什么?为什么使用 Recompose HOC 会删除 App
类组件内部函数?
谢谢。
最佳答案
您可以将函数 providerRef
传递给您的组件,然后像这样向它提供 App 实例
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
钩子(Hook)来使用 this 访问 innerComponent ref .playerComponentRef.getWrappedInstance()
,但是我不确定它在 recompose
中的可用性。
关于javascript - 使用重组组件作为 ref 时丢失功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151848/