Reactjs 如何将React Ref与样式化组件一起使用
我目前正在运行React 16.8.6和Styled Components 4.3.2,试图使用React.forwardRef时遇到了一个问题 在Comments.js中Reactjs 如何将React Ref与样式化组件一起使用,reactjs,styled-components,Reactjs,Styled Components,我目前正在运行React 16.8.6和Styled Components 4.3.2,试图使用React.forwardRef时遇到了一个问题 在Comments.js中 import CommentItem from './CommentItem'; class Comments extends Component { constructor(props) { super(props); this.items = []; } componentDidMount(
import CommentItem from './CommentItem';
class Comments extends Component {
constructor(props) {
super(props);
this.items = [];
}
componentDidMount() {
console.log(this.items);
}
render() {
const { comments } = this.props;
return (
<div>
{comments.length > 0 &&
comments.map((comment, i) => {
this.items[i] = React.createRef();
return (
<CommentItem
ref={this.items[i]}
key={comment.id}
comment={comment}
/>
);
})}
</div>
);
}
}
import CommentItem from./CommentItem';
类注释扩展组件{
建造师(道具){
超级(道具);
此参数为.items=[];
}
componentDidMount(){
console.log(this.items);
}
render(){
const{comments}=this.props;
返回(
{comments.length>0&&
comments.map((comment,i)=>{
this.items[i]=React.createRef();
返回(
);
})}
);
}
}
在CommentItem.js中
import styled from "styled-components";
import { Media } from "react-bulma-components";
const CommentMediaWrapper = styled(Media)`
position: relative;
`;
const CommentItem = React.forwardRef(
({ comment }, ref) => {
return (
<CommentMediaWrapper ref={ref}>
<div>...</div>
</CommentMediaWrapper>
);
}
);
export default CommentItem;
从“样式化组件”导入样式化;
从“react bulma components”导入{Media};
const CommentMediaWrapper=已设置样式(媒体)`
位置:相对位置;
`;
const CommentItem=React.forwardRef(
({comment},ref)=>{
返回(
...
);
}
);
导出默认项目;
在Comments.js中,将控制台一个数组[{current:null},…]
我不知道如何将ref传递到
CommentMediaWrapper
。我不想添加新元素外部或内部CommentMediaWrapper
。感谢您的帮助。我认为这里的问题更多地与您正在包装的react-bulma组件的库元素媒体有关。该组件公开一个名为domRef
的属性,该属性可用于将DOM引用传递到包装器下面的HTML元素
const CommentItem = React.forwardRef(
({ comment }, ref) => {
return (
<CommentMediaWrapper domRef={ref}>
<div>...</div>
</CommentMediaWrapper>
);
}
);
const CommentItem=React.forwardRef(
({comment},ref)=>{
返回(
...
);
}
);
我认为这里的问题更多地与您正在包装的react-bulma组件的库元素媒体有关。该组件公开一个名为domRef
的属性,该属性可用于将DOM引用传递到包装器下面的HTML元素
const CommentItem = React.forwardRef(
({ comment }, ref) => {
return (
<CommentMediaWrapper domRef={ref}>
<div>...</div>
</CommentMediaWrapper>
);
}
);
const CommentItem=React.forwardRef(
({comment},ref)=>{
返回(
...
);
}
);
感谢您的帮助,我检查文档,看到每个元素都会收到道具domRef,但当我给domRef prop时,它仍然不起作用。感谢您的帮助,我检查文档,看到每个元素都会收到道具domRef,但当我给domRef prop时,它仍然不起作用。