gpt4 book ai didi

javascript - 正在设置 React useImperativeHandle 和 forwardRef,引用似乎没有更新

转载 作者:行者123 更新时间:2023-12-04 12:39:48 25 4
gpt4 key购买 nike

我需要访问子组件的位置。据我了解,要访问子属性,我需要使用 useImperativeHandle 将子 API 添加到其 ref。此外,我需要使用 forwardRef 将引用从父级传递给子级。所以我这样做了:

const Text = React.forwardRef(({ onClick }, ref) => {
const componentAPI = {};
componentAPI.getLocation = () => {
return ref.current.getBoundingClientRect ? ref.current.getBoundingClientRect() : 'nope'
};
React.useImperativeHandle(ref, () => componentAPI);
return (<button onClick={onClick} ref={ref}>Press Me</button>);
});

Text.displayName = "Text";

const App = () => {
const ref = React.createRef();
const [value, setValue] = React.useState(null)

return (<div>
<Text onClick={() => setValue(ref.current.getLocation())} ref={ref} />
<div>Value: {JSON.stringify(value)}</div>
</div>);
};

ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app"></div>

如您所见,ref 没有 getBoundingClientRect 属性,但如果我这样做,它将按预期工作:

const App = () => {
const ref = React.createRef();
const [value, setValue] = React.useState(null)

return (<div>
<button ref={ref} onClick={() => setValue(ref.current.getBoundingClientRect()) } ref={ref}>Press Me</button>
<div>Value: {JSON.stringify(value)}</div>
</div>);
};

ReactDOM.render(<App />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app"></div>

那么我对useImperativeHanedleforwardRef的理解有什么问题吗?

最佳答案

要使用 useImperativeHandle,您需要像这样使用另一个 ref 实例:

const Text = React.forwardRef(({ onClick }, ref) => {
const buttonRef = React.useRef();

React.useImperativeHandle(
ref,
() => ({
getLocation: () => buttonRef.current.getBoundingClientRect()
}),
[buttonRef]
);

return (
<button onClick={onClick} ref={buttonRef}>
Press Me
</button>
);
});

如果您希望您的逻辑有效(使用相同的转发ref),这将起作用:

const Text = React.forwardRef(({ onClick }, ref) => {
React.useEffect(() => {
ref.current.getLocation = ref.current.getBoundingClientRect;
}, [ref]);

return (
<button onClick={onClick} ref={ref}>
Press Me
</button>
);
});

为什么您的示例不起作用?

因为 ref.current.getBoundingClientRectuseImperativeHandle 中分配它时不可用(尝试记录它)因为你实际上覆盖了按钮的 ref with useImperativeHandle(检查沙箱中的Text3ref.current 值在挂载后分配了getLocation) .

Edit admiring-darkness-o8bm4

关于javascript - 正在设置 React useImperativeHandle 和 forwardRef,引用似乎没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60599895/

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