我使用 new context API of React 构建了一个更高阶的组件我正在尝试找到一种能够访问包装子组件的引用(通过 ref())的方法。
tl/dr:本质上我想要 forward the ref从消费者
到实际组件。
这是一个具体的例子。 RootComponent
设置假定在所有包装子组件上公开的CoolProvider
的值。子组件使用 withCool()
进行包装,以便它可以访问 props.cool
。 (当然,在现实世界的示例中,一切都要复杂得多,并且有数十个组件。)
现在,无论是否知道子组件是否已被包装,我都希望能够通过 ref()
获取对它的引用,如 RootComponent
中所示,但不幸的是包装的组件不再支持 ref()
因为它们是功能性的!
查看此现场演示 ( https://jsfiddle.net/64t0oenz/3/ ) 并检查 Web 控制台。您将看到仅触发非包装组件的回调。
我的问题是:有没有办法将引用请求从 CoolConsumer
转发到实际组件,以便父组件可以访问它的引用?
const { Provider: CoolProvider, Consumer: CoolConsumer } = React.createContext();
const withCool = Component => props => (
<CoolConsumer>
{cool => <Component {...props} cool={cool} />}
</CoolConsumer>
);
class ChildComponent extends React.Component {
render() {
return this.props.cool ? (
<div>Isn't this cool?</div>
) : (
<div>Not so cool!</div>
);
}
}
const CoolChildComponent = withCool(ChildComponent);
class RootComponent extends React.Component {
render() {
return (
<CoolProvider value={true}>
<ChildComponent ref={(c) => { console.log('Normal child ref', c); }}/>
<CoolChildComponent ref={(c) => { console.log('Cool child ref', c); }}/>
</CoolProvider>
);
}
}
ReactDOM.render(<RootComponent />, document.querySelector('#cool'));
最佳答案
我明白了!使用 React 的 forwardRef
API 完全可以实现我正在寻找的东西。唯一需要的更改是替换
const withCool = Component => props => (
<CoolConsumer>
{cool => <Component {...props} cool={cool} />}
</CoolConsumer>
);
与
const withCool = Component => React.forwardRef((props, ref) => (
<CoolConsumer>
{cool => <Component {...props} cool={cool} ref={ref} />}
</CoolConsumer>
));
这是修改后的现场演示:https://jsfiddle.net/64t0oenz/4/ 打开开发控制台,您现在将看到 2 个控制台日志,打印对正常组件和酷组件的引用。 🎉
关于javascript - React 上下文消费者如何访问消费组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53200784/