dev*_*mat 11 javascript ref reactjs react-forwardref
我知道 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>
Run Code Online (Sandbox Code Playgroud)
还有我的 CircleButton 组件。像这样使用,它会产生警告。
const CircleButton = (props) => // gives the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
Run Code Online (Sandbox Code Playgroud)
警告:不能为函数组件提供引用。尝试访问此引用将失败。你的意思是使用 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>)
Run Code Online (Sandbox Code Playgroud)
请问div组件有一个状态?我不明白。是否在forwardRef做一些魔术并为 div 元素创建状态?
为什么如果我将 传递ref给Button组件它仍然会发出警告?
const CircleButton = forwardRef((props, ref) => // gives the warning
<Button ref={ref} shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />)
Run Code Online (Sandbox Code Playgroud)
如果我antd Button小时候直接通过,它会起作用。但这是因为我认为 antd 按钮有一个状态,因此它可以有 refs。
<Tooltip placement="left" title={"Lock slot"}> // doesn't give the warning
<Button shape="circle" size="small" style={{ marginRight: "8px" }} />
</Tooltip>
Run Code Online (Sandbox Code Playgroud)
正如警告所述,您无法在不使用 的情况下将引用分配给功能组件forwardRef。
为了访问任何组件的引用,需要创建组件的实例,并且仅为类组件创建实例,而调用或调用函数组件
从 v16.8.0 开始,React 引入了一个名为 的 API useRef,它允许您在功能组件中创建引用,这些引用可以在 HTML 节点、类组件或用 包裹的功能组件上使用forwardRef
另外:为了实现类组件中可用的相同行为ref,您可以使用forwardRefwithuseImperativeHandle钩子将功能组件中的某些函数或状态公开给父组件。
const CircleButton = forwardRef((props, ref) => {
const someFunction = () =>{}
useImperativeHandle(ref, () => ({
someFunc
}));
return (
<div>
<Button shape="circle" size="small" style={{ marginRight: "8px" }} {...props} />
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7700 次 |
| 最近记录: |