我正在尝试从另一个组件调用一个函数,使用老式的 react Class 样式我可以轻松地做到这一点,因为我试图挂钩我面临的所有此类问题
当我们使用参考调用 setText() 时,此代码不起作用:
export function MyComp(props, ref) {
const [theText, setText] = useState(props.theText);
return (
<div>
<h1>{theText}</h1>
<button
onClick={e => {
setText("clicked with inside button");
}}
>
inside button
</button>
<button
onClick={e => {
setText("not clicked");
}}
>
reinit
</button>
</div>
);
}
export const MyRefComp = React.forwardRef((props, ref) => (
<MyComp ref={ref} {...props}>
{props.children}
</MyComp>
));
function App() {
const compref = useRef();
return (
<div>
<MyRefComp ref={compref} theText="not clicked" />
<button
onClick={e => {
compref.current.setText("clicked with outside button");
}}
>
outside button
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这是可编辑的代码:https ://codesandbox.io/s/reactforwardrefproblem-ublk0
感谢您的帮助