我看到 React.forwardRef 似乎是将 ref 传递给子功能组件的认可方式,来自 react 文档:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)
但是,与简单地传递自定义道具相比,这样做有什么优势?:
const FancyButton = ({ innerRef }) => (
<button ref={innerRef} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton innerRef={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一优势可能是为 refs 提供了一致的 api,但还有其他优势吗?传递自定义道具是否会影响渲染时的差异并导致额外的渲染,肯定不会因为 ref 在current
字段中存储为可变状态?
例如,假设您想传递多个 refs(这可能表明代码异味,但仍然如此),那么我能看到的唯一解决方案是使用 customRef 道具。
我想我的问题是使用forwardRef
自定义道具的价值是什么?
我正在尝试将以下内容转换为使用React.memo
:
interface Props<TRowData> {
// props...
}
export function Table<TRowData>({
propA,
propB
}: Props<TRowData>) {
}
Run Code Online (Sandbox Code Playgroud)
像这样(不正确):
interface Props<TRowData> {
// props...
}
export const Table = memo<Props<TRowData>>(
({
propA,
propB
}) => {
})
Run Code Online (Sandbox Code Playgroud)
如何更正此语法?目前它有这个错误:
// Cannot find name 'TRowData'.
export const Table = memo<Props<TRowData>>(
~~~~~~~~
Run Code Online (Sandbox Code Playgroud)