首页 > 解决方案 > 隐式获取任何绑定元素子项的类型错误

问题描述

我正在将 jsx 代码转换为打字稿,其中我遇到了如下错误

绑定元素 'children' 隐式具有任何类型

我在 jsx 中的代码如下

const GoogleMap = ({ children, ...props }) => (
  <div style={{ height: '80vh', width: '100%' }}>
    <GoogleMapReact
      bootstrapURLKeys={{
        key: environment.googleApiKey,
      }}
      {...props}
    >
      {children}
    </GoogleMapReact>
  </div>
);

GoogleMap.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.arrayOf(PropTypes.node),
  ]),
};

GoogleMap.defaultProps = {
  children: null,
};

export default GoogleMap;

上面的代码现在转换为打字稿如下

const GoogleMap = ({ children, ...props }) => (
  <div style={{ height: '80vh', width: '100%' }}>
    <GoogleMapReact
      bootstrapURLKeys={{
        key: environment.googleApiKey,
      }}
      {...props}
    >
      {children}
    </GoogleMapReact>
  </div>
);

export default GoogleMap;

我已经尝试将孩子设置为任何但它不起作用。因为我是打字稿的新手,所以我无法弄清楚

标签: reactjstypescript

解决方案


您应该像这样为组件分配一个接口

interface GoogleMapProps {
   exampleprop: string
   exampleprop: number
}

const GoogleMap: React.FC<GoogleMapProps> = ({ children, ...props }) => (
  <div style={{ height: '80vh', width: '100%' }}>
    <GoogleMapReact
      bootstrapURLKeys={{
        key: environment.googleApiKey,
      }}
      {...props}
    >
      {children}
    </GoogleMapReact>
  </div>
);

export default GoogleMap;

React.FC代表 React.FunctionalComponent 。这包括 children 属性,它返回一个返回 JSX 的函数。传递给的接口React.FC是所有其他道具


推荐阅读