无状态函数组件不能给出refs [英] Stateless function components cannot be given refs

查看:576
本文介绍了无状态函数组件不能给出refs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试访问组件中的一些引用。但我在控制台中有这个错误。
withRouter.js:44警告:无状态函数组件不能给出refs(请参阅RegisterForm创建的FormInputText中的refpseudo)。尝试访问此参考文件将失败。

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.

这是我的组件:

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

当我点击按钮时我得到了<$控制台中的c $ c> Object {pseudo:null} 。我希望一个对象 null

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

我不确定为什么这不起作用。请注意,我的反应树使用 mobx-react

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

推荐答案

参考资料不适用于无状态组件。它在文档中进行了解释

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


由于无状态函数没有后备实例,因此无法将ref附加到无状态函数组件。

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

写入时的无状态组件实际上有实例(它们在内部包装到类中)但是你无法访问它们,因为React团队将来会进行优化。请参见 https://github.com/facebook/react/issues/4936#issuecomment- 179909980

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

这篇关于无状态函数组件不能给出refs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆