I created a method in useImperativeHandle hook in my child component. Then, I can access it from parent component perfectly. Like below example. But, I can't access it from child component. In an other saying, focus from parent button working, but focus from child not working. How can I do this?
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…