React Window如何传递组件?

时间:2019-05-21 18:06:26

标签: reactjs react-window

我正在尝试实现react-window,但是我不确定如何传递具有其自身属性的组件

如果我有这样的东西

{
  items.map(
    (item, index) => {
      <MyComponent
        key={key}
        item={item}
      />;
    }
  );
}

如何制作变量列表?

该示例未显示如何执行此操作

import { VariableSizeList as List } from 'react-window';

// These row heights are arbitrary.
// Yours should be based on the content of the row.
const rowHeights = new Array(1000)
  .fill(true)
  .map(() => 25 + Math.round(Math.random() * 50));

const getItemSize = index => rowHeights[index];

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

const Example = () => (
  <List
    height={150}
    itemCount={1000}
    itemSize={getItemSize}
    width={300}
  >
    {Row}
  </List>
);

1 个答案:

答案 0 :(得分:1)

这个例子确实令人困惑。 This example展示了如何使用react-window处理一系列数据,而不是首页显示的生成示例:

class ComponentThatRendersAListOfItems extends PureComponent {
  render() {
    // Pass items array to the item renderer component as itemData:
    return (
      <FixedSizeList
        itemData={this.props.itemsArray}
        {...otherListProps}
      >
        {ItemRenderer}
      </FixedSizeList>
    );
  }
}

// The item renderer is declared outside of the list-rendering component.
// So it has no way to directly access the items array.
class ItemRenderer extends PureComponent {
  render() {
    // Access the items array using the "data" prop:
    const item = this.props.data[this.props.index];

    return (
      <div style={this.props.style}>
        {item.name}
      </div>
    );
  }
}

虽然代码示例中未提供itemsArray,但表面上您会在其中包含传递给ItemRenderer所需的道具,例如此处显示的name。这会使您的用法看起来像这样:

<ComponentThatRendersAListOfItems
  itemsArray={[{ name: "Test 1" }, { name: "Test 2" }]}
/>