【问题标题】:How to type the index and style props passed to Row function using React-Window如何使用 React-Window 键入传递给 Row 函数的索引和样式道具
【发布时间】:2021-03-19 16:01:50
【问题描述】:

我正在尝试键入以下两个传递给 Row 函数的参数。

//https://github.com/bvaughn/react-window

import * as React from "react";
import styled from "styled-components";
import { FixedSizeList as List } from "react-window";
import AutoSizer from "react-virtualized-auto-sizer";

const StyledSection = styled.section`
  width: 100vw;
  height: 100vh;
  background: #C0C0C0;
`;

const Row = ({ index, style }) => (
  <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
    Row {index}
  </div>
);

const Scroller = () => {
  return (
    <StyledSection>
      <AutoSizer>
        {({ height, width }) => {
          return (
            <List height={height} width={width} itemSize={20} itemCount={300}>
              {Row}
            </List>
          );
        }}
      </AutoSizer>
    </StyledSection>
  );
};

export { Scroller };

所以下面的代码 typescript 的 sn-p 将 index 和 style 参数推断为 type any。我试图将索引的类型内联为数字,但编译器说索引未定义。

   const Row = ({ index, style }) => (
      <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
        Row {index}
      </div>
    );

关于如何为这两个参数提供类型的任何想法。 react-window 有自己的 d.ts 文件。这是工作代码框 - https://codesandbox.io/s/infinite-scroller-52b7d?file=/src/Scroller.tsx

【问题讨论】:

    标签: typescript react-window


    【解决方案1】:

    这就是你想要的吗?

    import { CSSProperties } from 'react';
    
    const Row = ({ index, style }: { index: number; style: CSSProperties; }) => (
      <div className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
        Row {index}
      </div>
    );
    

    您仍然可以在使用对象解构时添加类型。您还可以使用 IDE 查找 style 的类型,在 style={style} 的第一个 style 上使用 goto declaration。 (jetbrain IDE 中的 ctrl-b 或 ctrl-q,不知道 VScode,抱歉)。

    【讨论】:

    • 是的,是的,是的。谢谢你。我试图在解构的道具对象内输入,所以在 { index: number, style} 内。再次感谢 CSSProperties 和工具提示。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2019-11-11
    • 2021-10-28
    • 2020-06-11
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多