Skip to content

APILoader组件在TypeScript中作为JSX标签不可用 #311

Closed
@kqhasaki

Description

@kqhasaki

APILoader的返回值类型定义为ReactNode,不能直接作为JSX标签中使用,这样按照官方文档的标签写法在TypeScript项目中出错。

import React from 'react';
import ReactDOM from 'react-dom';
import { Map, APILoader } from '@uiw/react-amap';

const Demo = () => (
  <APILoader akey="a7a90e05a37d3f6bf76d4a9032fc9129">
    <Map style={{ height: 100, marginBottom: 10 }} />
    <div style={{ border: '1px solid red' }}>
      <Map style={{ height: 100 }} />
    </div>
  </APILoader>
);

export default Demo

请确认是否必要返回ReactNode类型,例如这里分支中返回children应该可以用Fragment包裹一下,确保让组件返回ReactElement类型。

/**
 * APILoader 用于加载百度地图依赖
 */
export const APILoader = (props: APILoaderProps) => {
  const { children, ...config } = props;
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<Error>();
  useEffect(() => {
    const aKey = config.akey || config.akay || '';
    const plugins = config.plugins || (config.plugin ? config.plugin.split(',') : []);
    load({
      key: aKey,
      plugins,
      version: config.version || '2.0',
      AMapUI: config.AMapUI,
      Loca: config.Loca,
    })
      .then(() => {
        setError(undefined);
        setLoaded(true);
      })
      .catch((err) => {
        setError(err);
      });
  }, [config.akey, config.akay]);
  if (error) {
    return <div style={{ color: 'red' }}>{error.message}</div>;
  } else if (loaded) {
    return children;
  }
  return null;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions