How can I attach to a stateless component's ref in React?

后端 未结 5 2239
悲哀的现实
悲哀的现实 2020-12-08 03:48

I am looking to create a stateless component who\'s input element can be validated by the parent component.

In my example below, I am running into a pro

5条回答
  •  半阙折子戏
    2020-12-08 04:29

    You can useuseRef hook which is available since v16.7.0-alpha.

    EDIT: You're encouraged to use Hooks in production as of 16.8.0 release!

    Hooks enable you to maintain state and handle side effects in functional components.

    function TextInputWithFocusButton() {
      const inputEl = useRef(null);
      const onButtonClick = () => {
        // `current` points to the mounted text input element
        inputEl.current.focus();
      };
      return (
        <>
          
          
        
      );
    }
    

    Read more in Hooks API documentation

提交回复
热议问题