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

后端 未结 5 2245
悲哀的现实
悲哀的现实 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:08

    EDIT: You now can with React Hooks. See the answer by Ante Gulin.

    You can't access React like methods (like componentDidMount, componentWillReceiveProps, etc) on stateless components, including refs. Checkout this discussion on GH for the full convo.

    The idea of stateless is that there isn't an instance created for it (state). As such, you can't attach a ref, since there's no state to attach the ref to.

    Your best bet would be to pass in a callback for when the component changes and then assign that text to the parent's state.

    Or, you can forego the stateless component altogether and use an normal class component.

    From the docs...

    You may not use the ref attribute on functional components because they don't have instances. You can, however, use the ref attribute inside the render function of a functional component.

    function CustomTextInput(props) {
      // textInput must be declared here so the ref callback can refer to it
      let textInput = null;
    
      function handleClick() {
        textInput.focus();
      }
    
      return (
        
    { textInput = input; }} />
    ); }

提交回复
热议问题