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

问题描述 投票:0回答:2

我正在尝试使用react-virtualized渲染卡清单。该特定组件上的posts数据作为prop从父级传递。这是我当前在组件类中拥有的。

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道具?我只是想为posts属性数组中的每个帖子返回一个PostItem组件。

reactjs react-virtualized
2个回答
0
投票

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


0
投票

您可以使用rowRenderer.Checkout签名here中收到的父项来访问rowRenderer中发送的属性。>

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]}/>
    );
 }
}

应该可以解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.