我知道 refs 用于直接访问 DOM 元素而不更改状态。我读到过不能给函数组件提供 refs,因为它们没有状态。
引用无法附加到函数组件。虽然我们可以定义 refs 并将其附加到 DOM 元素或类组件。底线是 - 函数组件没有实例,所以你不能引用它们。
摘自:https://blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/ 我仍然不明白。
我正在使用 Ant Design 的 Tooltip 组件(https://ant.design/components/tooltip/),Button 组件和自定义 CircleButton 组件。
给出以下 JSX:
引用无法附加到函数组件。虽然我们可以定义 refs 并将其附加到 DOM 元素或类组件。底线是 - 函数组件没有实例,所以你不能引用它们。
摘自:https://blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/ 我仍然不明白。
我正在使用 Ant Design 的 Tooltip 组件(https://ant.design/components/tooltip/),Button 组件和自定义 CircleButton 组件。
给出以下 JSX:
<Tooltip placement="left" title={"Lock slot"}>
<CircleButton onClick={() => execute(client.close)} icon={<LockOutlined />} disabled={loading} />
</Tooltip>
还有我的CircleButton组件。如果像这样使用它,将会生成警告。
const CircleButton = (props) => // gives the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
警告:无法为函数组件赋予ref。尝试访问此ref将失败。您是否意味着使用React.forwardRef()?
请注意,尽管出现警告,但一切均按预期工作。
如果我按以下方式进行编辑,它会正常工作,为什么?
const CircleButton = forwardRef((props, ref) => // doesn't give the warning
<div ref={ref}>
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
</div>)
div
组件有状态吗?我不明白。是forwardRef
在为
元素创建状态吗?
如果我直接将
那么,如果我将ref
传递给Button
组件,为什么它仍然会出现警告?
const CircleButton = forwardRef((props, ref) => // gives the warning
<Button ref={ref} shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />)
如果我直接将
antd
的Button
作为子元素传递,它是可以工作的。但这是因为我认为 antd按钮具有状态,因此可以拥有refs。<Tooltip placement="left" title={"Lock slot"}> // doesn't give the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} />
</Tooltip>
input
元素的,这个例子帮助我完全理解了它:https://dev59.com/h8X5oIgBc1ULPQZF3D4_#73567453 - Andru