gpt4 book ai didi

reactjs - 从同一函数访问 Useimperativehandle 方法

转载 作者:行者123 更新时间:2023-12-02 02:27:01 25 4
gpt4 key购买 nike

我在子组件的 useImperativeHandle Hook 中创建了一个方法。然后,我可以完美地从父组件访问它。就像下面的例子。但是,我无法从子组件访问它。换句话说,focus from parent 按钮有效,但 focus from child 不起作用。我该怎么做?

CODESANDBOX LINK

fancyInput.js

import React, { forwardRef } from "react";

const FancyInput = forwardRef((props, ref) => {
const inputRef = React.useRef();
React.useImperativeHandle(ref, () => ({
activateFocus: () => {
inputRef.current.focus();
}
}));

return (
<div>
<input ref={inputRef} />
<br /> <br />
<button onClick={() => inputRef.current.activateFocus()}>
Focus from children
</button>
</div>
);
});

export default FancyInput;

index.js

import React from "react";
import ReactDOM from "react-dom";
import FancyInput from "./fancyInput";

function App() {
const inputRef = React.useRef();
return (
<div className="App">
<FancyInput ref={inputRef} />
<br />
<button onClick={() => inputRef.current.activateFocus()}>
Focus from parent
</button>
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

最佳答案

activateFocus 的函数声明移到 useImperativeHandle 之外,但保留其中的引用。像这样:

const FancyInput = forwardRef((props, ref) => {
const inputRef = React.useRef();
const activateFocus = () => inputRef.current.focus();
React.useImperativeHandle(ref, () => ({
activateFocus
}));

return (
<div>
<input ref={inputRef} />
<br /> <br />
<button onClick={activateFocus}>
Focus from children
</button>
</div>
);
});

关于reactjs - 从同一函数访问 Useimperativehandle 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65517803/

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