【问题标题】:How to use React Ref with Styled Component如何将 React Ref 与样式化组件一起使用
【发布时间】:2020-02-07 16:11:07
【问题描述】:

我目前正在运行 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() {
    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>
    );
  }
}

在 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;

在 Comments.js 中将控制一个数组 [{ current: null },...] 我不知道如何将 ref 传递给CommentMediaWrapper。我不想在CommentMediaWrapper 外部或内部添加新元素。感谢您的帮助。

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    我认为这里的问题更多地与您正在包装的 react-bulma-components 中的库元素 Media 有关。该组件公开了一个名为 domRef 的 prop,可用于将 DOM 引用传递给包装器下的 HTML 元素。

    const CommentItem = React.forwardRef(
      ({ comment }, ref) => {
        return (
          <CommentMediaWrapper domRef={ref}>
            <div>...</div>
          </CommentMediaWrapper>
        );
      }
    );
    

    Github Reference

    【讨论】:

    • 感谢您的帮助,我检查了文档,发现每个元素都会收到道具 domRef,但是当我提供 domRef 道具时,它仍然没有工作。
    猜你喜欢
    • 2018-10-17
    • 2017-09-19
    • 2019-02-05
    • 2018-03-17
    • 2018-11-22
    • 2019-12-10
    • 2020-09-17
    • 2019-09-01
    • 2021-11-01
    相关资源
    最近更新 更多