代码之家  ›  专栏  ›  技术社区  ›  FacundoGFlores

以适当的方式键入对象作为道具

  •  0
  • FacundoGFlores  · 技术社区  · 7 年前

    目前我有以下组件

    搜索按钮.tsx

    export interface Props {
      // some other props
      onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
    }
    
    export const SearchButton: React.SFC<Props> = ({
      // other props
      onClick,
    })
    

    Popover.tsx公司

    interface ButtonComponentProps {
      onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
    }
    
    interface Props {
      buttonComponent: React.ComponentType<ButtonComponentProps>;
    }
    
    class FilterPopover extends React.Component<Props, State> {
        render() {
            const {buttonComponent: BtnComponent} = this.props;
            return (
                <div>
                    //...
                    <BtnComponent onClick={this.open} />
                </div>
            )
        }
    
    }
    

    <Popover buttonComponent={SearchButton}/>
    

    但我有一个不匹配的类型:

    The expected type comes from property 'buttonComponent' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Popover> & Readonly<{ children?: ReactNode; }> & Readonly<Props>'
    

    所以如果我把道具从 Popover.tsx

    interface ButtonComponentProps {
      onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
    }
    

    然后接口匹配,但Typescript是如何通过 SearchButton ? 这样匹配接口可以吗?为什么那些应该是一样的?

    React 16.4.1类型脚本3.0.1

    1 回复  |  直到 7 年前
        1
  •  1
  •   Matt McCutchen    7 年前

    TypeScript正在比较 SearchButton ,这是 React.SFC</*SearchButton*/ Props> ,到 buttonComponent 支柱 FilterPopover ,这是 React.ComponentType<ButtonComponentProps> the definition of React.ComponentType<P> ,另一种选择是 React.StatelessComponent<P> ,这是 React.SFC<P> 反应。SFC<P> 是不变的 P 第页 ( 搜索按钮 Props ButtonComponentProps )必须完全匹配。

    你可能认为一个组件接受一个可选的道具 onClick 应该可以用来代替接受所需属性的组件,因为这意味着将始终设置可选属性。然而,情况并非如此,因为 the optional propTypes and defaultProps fields of a stateless component 已经宣布了。我不熟悉类型声明设计背后的详细原理。最简单的方法就是精确匹配道具界面。

    推荐文章