我正在尝试在两个未直接链接的组件之间使用useRef
。
如何?
由于 useRef 是一个钩子(Hook),我不能将其添加到某个文件中并共享它。
export const someRef = React.useRef(); // not possible, it needs to be inside a jsx component
我正在尝试找到一种在全局范围内使用它的方法,类似于如果这是状态的话,这将是可能的。
如果这是状态,我只会使用现有的 Redux
实现或 context
。
请告知如何对 useRef
执行相同的操作。我没有下面的 Compo2 组件,因此我需要在这里坚持使用引用。
P.S:我可以通过向下 6 层进行一些螺旋钻探来实现这一目标。.尽量不这样做。
// place reference on this component
export const Compo1 = () => {
return (
<div ref={someRef}>
text 1
</div>
);
};
// same someRef reference passed as a prop here from some other component which doesn't talk to Compo1.
export const Compo2 = ({
someRef,
}) => {
// Do something with the reference value
return (
<div>
text 2
</div>
);
};
最佳答案
您可以创建一个新的全局变量,例如:
export const inputRef = { current: null };
function Input() {
return (
<label>
<input type="text" ref={inputRef} placeholder="Type something" />
</label>
);
}
export default Input;
然后你可以像平常一样使用它,通过 import.o
import Input, { inputRef } from "./Input";
function Container({ children }) {
function handleClick() {
inputRef.current.focus();
}
return (
<div
onClick={handleClick}
style={{
padding: 16,
backgroundColor: "yellow",
}}
>
{children}
</div>
);
}
export default function App() {
return (
<Container>
<Input />
</Container>
);
}
参见此处a live version
关于javascript - 如何在全局范围内共享 useRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76094303/