[英]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?我在这里做错了什么?
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.