如何将 prop 传递给反应虚拟化的 rowrender

how to pass prop into rowrender of react-virtualized

我正在尝试使用 react-virtualized 呈现卡片列表。此特定组件上的 posts 数据作为 prop 从父级传递。这就是我目前在我的组件 class 中拥有的内容。

state = {
    listHeight: 1000,
    listRowHeight: 800,
    listRowWidth: 1000,
    rowCount: 10
}


rowRenderer ({ index, key, style, posts }) {
    if (!posts) {
        return <div></div>
    } else {
    return (
        <PostItem key={key} style={style} post={posts[index]}/>
    );
    }
}


render() {
    return (
        <div className="ui container">
            <div id="postListContainer" className="ui relaxed list">
                <List 
                    width={this.state.listRowWidth}
                    height={this.state.listHeight}
                    rowHeight={this.state.listRowHeight}
                    rowRenderer={this.rowRenderer}
                    rowCount={this.state.rowCount}
                    posts={this.props.posts}
                />
            </div>
        </div>
        );
    }
}

我对 rowCount 进行了硬编码,因为我知道我的 posts 数组中目前有 10 个项目。仅供参考,这是我成功呈现整个列表的原始代码。

renderPosts() {
    return this.props.posts.map(post => {
        return (
            <PostItem key={post._id} post={post}/>
        );
    })
}

render() {
    return (
        <div className="ui container">
            <div id="postListContainer" className="ui relaxed list">
                {this.renderPosts()}
            </div>
        </div>
        );
    }
}

我目前遇到的问题是我无法访问从我的 rowRenderer 函数传递到该组件的道具,所以它给了我一个未定义的错误。所以我的问题是,如何访问 rowRenderer 函数中的 posts 道具?我只是想 return 为 posts 道具数组中的每个 post 创建一个 PostItem 组件。

rowRenderer 的签名如下所示:

function rowRenderer ({
  index,       // Index of row
  isScrolling, // The List is currently being scrolled
  isVisible,   // This row is visible within the List (eg it is not an overscanned row)
  key,         // Unique key within array of rendered rows
  parent,      // Reference to the parent List (instance)
  style        // Style object to be applied to row (to position it);
               // This must be passed through to the rendered row element.
}) { .. }

因此您无法通过参数访问道具。您可以通过实例变量 this.

访问道具

当您将处理程序传递给 List 时,您应该像这样绑定处理程序:

<List 
    ...
    rowRenderer={this.rowRenderer.bind(this)}
/>

然后在 rowRenderer 中你可以简单地访问 this.props.posts

您可以使用在 rowRenderer.Checkout 签名 here

中收到的父级访问 rowRenderer 方法中从 List 标记发送的属性
rowRenderer ({ index, key, style, parent }) {
 const posts = parent.props.posts; 
 if (!posts) {
    return <div></div>
 } else {
    return (
      <PostItem key={key} style={style} post={posts[index]}/>
    );
 }
}

这应该可以解决您的问题 problem.Also 您可以通过将此变量绑定到 rowrenderer 方法或通过 ES6 语法来访问 props

 rowRenderer = ({ index, key, style, parent }) => {
 const posts = parent.props.posts;
 const { someThing } = this.props; 
 if (!posts) {
    return <div></div>
 } else {
    return (
      <PostItem key={key} style={style} post={posts[index]}/>
    );
 }
}