在 React 样式组件上使用“ref”不起作用

新手上路,请多包涵

我在将 ref 与样式化组件一起使用时遇到困难。当我尝试像下面这样在我的类方法中访问它们时,出现以下错误:

Edit.js:42 Uncaught TypeError: this…..包含不是函数

  constructor(props) {
    ....
    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
   }
----------
  setWrapperRef = (node) => {
    this.wrapperRef = node;
  }
  handleEdit = (e) => {
    e.preventDefault();
    this.props.onEdit(this.props.id, this.state.title);
  }
----------
<Wrapper onSubmit={this.handleEdit} ref={this.setWrapperRef}>
  ...
</Wrapper>

我从 这个问题 中找到了代码

我在这里做错了什么?

原文由 nikjohn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 654
1 个回答

我自己找到了答案。解决方案是使用 innerRef 而不是 ref 因为 ref 本身指向样式化组件而不是 DOM 节点。

可以在 GitHub 上找到详细的讨论

原文由 nikjohn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题