Stateless function components cannot be given refs

2020-08-26 11:10发布

问题:

I try to access some refs in my component. But I have this error in the console. withRouter.js:44 Warning: Stateless function components cannot be given refs (See ref "pseudo" in FormInputText created by RegisterForm). Attempts to access this ref will fail.

Here is my component:

class RegisterForm extends React.Component {

  render() {
    return (
      <form action="">
        <FormInputText ref="pseudo"  type="text" defaultValue="pseudo"/>
        <input type="button" onClick={()=>console.log(this.refs);} value="REGISTER"/>
      </form>
    );
  }
}

Plus when I click on the button I got Object {pseudo: null}in the console. I would expect an object instead null.

I am not sure to understand why this is not working. Note that my react tree uses mobx-react.

回答1:

Refs do not work with stateless components. It is explained in the docs

Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component.

Stateless components at the moment of writing actually have instances (they are wrapped into classes internally) but you can not access them because React team is going to make optimizations in the future. See https://github.com/facebook/react/issues/4936#issuecomment-179909980



回答2:

You could also try using recompose it has a function called toClass.

Takes a function component and wraps it in a class. This can be used as a fallback for libraries that need to add a ref to a component, like Relay.

If the base component is already a class, it returns the given component.