我知道 refs 用于直接访问 DOM 元素而不改变状态。我读到无法为功能组件提供引用,因为它们没有状态。
Refs 不能附加到函数组件。虽然,我们可以定义 refs 并将它们附加到 DOM 元素或类组件。底线是——函数组件没有实例,所以你不能引用它们。
取自:https : //blog.logrocket.com/cleaning-up-the-dom-with-forwardref-in-react/
我还是不明白。
我正在使用TooltipAnt Design ( 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} />
警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 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做一些魔法并为 div 元素创建一个状态吗?
为什么如果我将 传递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>