gpt4 book ai didi

javascript - 如何在基于类的组件中使用 React.forwardRef?

转载 作者:IT王子 更新时间:2023-10-29 02:50:19 26 4
gpt4 key购买 nike

我正在尝试使用 React.forwardRef,但对如何让它在基于类的组件(而非 HOC)中工作感到困惑。

文档示例使用元素和功能组件,甚至将类包装在高阶组件的函数中。

因此,从类似 this 的内容开始在他们的 ref.js 文件中:

const TextInput = React.forwardRef(
(props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);

而是将其定义为如下内容:

class TextInput extends React.Component {
render() {
let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
return <input type="text" placeholder="Hello World" ref={ref} />;
}
}

class TextInput extends React.Component {
render() {
return (
React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
);
}
}

只工作:/

此外,我知道我知道,ref 不是 react 方式。我正在尝试使用第三方 Canvas 库,并想在单独的组件中添加他们的一些工具,所以我需要事件监听器,所以我需要生命周期方法。以后可能会走不同的路线,但我想试试这个。

文档说这是可能的!

Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

来自 note in this section.

但随后他们继续使用 HOC 而不仅仅是类。

最佳答案

始终对 ref 使用相同属性的想法可以通过使用助手代理类导出来实现。

class ElemComponent extends Component {
render() {
return (
<div ref={this.props.innerRef}>
Div has a ref
</div>
)
}
}

export default React.forwardRef((props, ref) => <ElemComponent
innerRef={ref} {...props}
/>);

所以基本上,我们被迫使用不同的 prop 来转发 ref,但这可以在 hub 下完成。重要的是公众将其用作正常引用。

关于javascript - 如何在基于类的组件中使用 React.forwardRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com