Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

reactjs - Access Useimperativehandle method from same function

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Move activateFocus's function declaration outside of useImperativeHandle, but keep the reference in it. Like this:

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>
  );
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...