Stateless function components cannot be given refs

孤人 提交于 2019-12-10 04:15:00

问题


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.



来源:https://stackoverflow.com/questions/38619265/stateless-function-components-cannot-be-given-refs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!