gpt4 book ai didi

javascript - 直接在 render 函数中使用 React.forwardRef

转载 作者:行者123 更新时间:2023-11-30 08:18:49 25 4
gpt4 key购买 nike

直接在另一个组件的渲染函数中使用 React.forwardRef 方法是否安全 -

例子-

function Link() {
// --- SOME EXTENSIVE LOGIC AND PROPS CREATING GOES HERE ---
// --- OMITTED FOR SIMPLICITY ---

// TO DO: Remove forward ref as soon Next.js bug will be fixed -
// https://github.com/zeit/next.js/issues/7915

// Please note that Next.js Link component uses ref only to prefetch link
// based on its availability in view via IntersectionObserver API -
// https://github.com/zeit/next.js/blob/canary/packages/next/client/link.tsx#L119
const TempShallow = React.forwardRef(props =>
cloneElement(child, {
...props,
...baseProps,
onClick: handleClick
})
);

return (
<NextLink href={href} as={as} prefetch={prefetch} passHref {...otherProps}>
<TempShallow />
</NextLink>
);
}

如您所见,这是针对 Next.js v9 中错误的临时解决方法 - https://github.com/zeit/next.js/issues/7915 .

最佳答案

注意 forwardRef影响协调:元素总是在父重新渲染时重新创建。

function App() {
const [,setState] = useState(null);
const Input = React.forwardRef((props, ref) => <input {...props} />)
return (
<div className="App">
<h1>Input something into inputs and then click button causing re-rendering</h1>
<Input placeholder="forwardRef" />
<input placeholder="native" />
<button onClick={setState}>change state to re-render</button>
</div>
);
}

点击按钮 forwardRef 后您可能会看到-ed 输入被删除并重新创建,因此它的值变为空。

不确定这对 <Link> 是否重要但总的来说,这意味着您希望每个生命周期只运行一次的事情(比如在 componentDidMountuseEffect(...,[]) 中获取数据作为替代)将更频繁地发生。

因此,如果在这种副作用和模拟警告之间做出选择,我宁愿忽略警告。或者自己创建 <Link >这不会引起警告。

[UPD] 遗漏了一件事:React 检查 forwardRef在这种情况下通过引用。所以如果你做 forwardRef来自 render (所以它在引用上是相同的)它不会被重新创建:

const Input = React.forwardRef((props, ref) => <input {...props} />)

function App() {
const [,setState] = useState(null);
return (
<div className="App">
<h1>Input something into inputs and then click button causing re-rendering</h1>
<Input placeholder="forwardRef" />
<input placeholder="native" />
<button onClick={setState}>change state to re-render</button>
</div>
);
}

但我仍然相信忽略警告比引入这样的解决方法更安全。

上面的代码对我来说可读性较差并且令人困惑(“为什么 ref 根本没有被处理?是故意的吗?为什么这个 forwardRef 在这里而不是在组件的文件中?”)

关于javascript - 直接在 render 函数中使用 React.forwardRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337436/

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