简体   繁体   English

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

[英]Using 'ref' on React Styled Components is not working

I am having difficulty using ref s with Styled Components.我在使用带有样式组件的ref时遇到了困难。 When I try to access them in my class methods like below, I get the following error:当我尝试在下面的类方法中访问它们时,出现以下错误:

Edit.js:42 Uncaught TypeError: this.....contains is not a function Edit.js:42 Uncaught TypeError: this.....contains 不是函数

  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>

I found the code from this question我从这个问题中找到了代码

What am I doing wrong here?我在这里做错了什么?

I found the answer myself.我自己找到了答案。 The solution is to use innerRef instead of ref as the ref itself points to the Styled Component and not the DOM node.解决方案是使用innerRef而不是ref因为ref本身指向样式化组件而不是 DOM 节点。

A detailed discussion can be found on GitHub详细的讨论可以在GitHub找到

If you extend another component in styled ref forwarding requires efford.如果您在样式化ref转发中扩展另一个组件需要 efford。 so my solution was extending that component with as prop.所以我的解决方案是使用as prop 扩展该组件。

before:前:

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} />
}

after:后:

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} />
}

    const StyledComponent = styled.div.attrs(({ref}) => ({
      ref: ref,
    }))``

    const App = () => {
      const anyRef = useRef();

      return <StyledComponent ref={anyRef}/>
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM