【问题标题】:Using 'ref' on React Styled Components is not working在 React 样式组件上使用 'ref' 不起作用
【发布时间】:2018-11-22 01:25:17
【问题描述】:

我在使用带有样式组件的refs 时遇到了困难。当我尝试在下面的类方法中访问它们时,出现以下错误:

Edit.js:42 Uncaught TypeError: this.....contains is not a function

  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>

我从this question找到了代码

我在这里做错了什么?

【问题讨论】:

  • ★ 从 styled-components v4 使用 ref 属性可以正常工作 → Docs link

标签: javascript reactjs dom ref styled-components


【解决方案1】:

如果您以 ref 样式扩展另一个组件,则转发需要付出努力。所以我的解决方案是使用as prop 扩展该组件。

之前:

import { useRef } from 'react'
import styled from 'styled-components'

const Card = styled.div``
const Block = styled(Card)``

const Component = () => {
    const ref = useRef(null);
    return <Card ref={ref} />
}

之后:

import { useRef } from 'react'
import styled from 'styled-components'

const Card = styled.div``
const Block = styled.div``

const Component = () => {
    const ref = useRef(null);
    return <Block as={Card} ref={ref} />
}

【讨论】:

    【解决方案2】:

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

    详细讨论可以在GitHub找到

    【讨论】:

    • 对于 v4 及以上版本,请直接使用 ref 属性。
    • 我收到了来自 Emotion 的警告,innerRef 将来会被弃用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2020-11-03
    • 2021-12-13
    • 2021-05-12
    • 2020-05-11
    • 2019-06-04
    • 2018-12-17
    相关资源
    最近更新 更多