错误:元素类型无效:预期为字符串或类/函数,但得到:未定义。导入错误

时间:2020-10-02 14:30:04

标签: reactjs typescript

下一个错误:

错误:元素类型无效:预期为字符串(对于内置 组件)或类/函数(用于复合组件),但得到: 未定义。您可能忘记了从文件中导出组件 是在其中定义的,或者您可能混淆了默认导入和命名导入。

我想在父组件中调用子函数。我尝试使用useRef,forwardRef和useImperativeHandle

父组件:

import Tree from '@c-tree'    


const NavTree: FunctionComponent = () => {
  
  const refTree = useRef();

  const tree = () => {
    if (d?.items && status === 'idle') {
      return (
        <Tree onNodeClickCallback={onClick} ref={refTree}>
          {d.items.map(s => (
            <Tree.Asset
              key={s.id}
              name={s.name}
              dataSelected={`${s.id}`}
              item={{
                name: s.name,
                tenantID: s.id,
                type: s?.tree?.name,
                children: [],
              }}
            />
          ))}
        </Tree>
      );
    }
  };

  return (
    <SideBar
      title={title}
    >
      <Box display="flex" flexDirection="column" height="100%">
        <StyledBox>{tree()}</StyledBox>
      </Box>
    </SideBar>
  );
};

export default NavTree;

子组件:

interface TreeStatic {
  Group: typeof TreeGroup;
  Asset: typeof TreeNode;
}

type TreeComponent = ForwardRefExoticComponent<PropsWithRef<ITreeProps>> & TreeStatic;

interface ITreeProps {
  data?: {
    type: string;
    name: string;
    tenantID: number;
    children?: Array<Object>;
  }[];
  ref: any;
}

const Tree = ({
  data,
  ref
}: ITreeProps) => {
  const [contextValues, setContextValues] = useState({
    selected: null,
    opened: {},
  });
 
  useImperativeHandle(ref, () => ({
    handleCurrentSelected: (selectedName: string) => {
      setContextValues({
      ...contextValues,
      selected: selectedName,
      opened: {
        ...contextValues.opened,
        [selectedName]: !contextValues.opened[selectedName] || false,
      },
    });
  }}
  ));

  return (
    <TreeContext.Provider value={contextValues}>
        {
          React.Children.map(children, child => {
            return React.cloneElement(child, childrenProps);
          })
        }
    </TreeContext.Provider>
  );
};

Tree.Group = TreeGroup;
Tree.Asset = TreeNode;

export default forwardRef(Tree) as TreeComponent;

1 个答案:

答案 0 :(得分:0)

我已经完成exported const Tree并进行了下一次导入:

import { Tree } from '@c-tree';

旧导入

import Tree from '@c-tree';

问题出在进口上。