如何解决 React Type {children: Element} has no properties in common with type IntrinsicAttribute

React.js 错误“Type {children: Element} has no properties in common with type IntrinsicAttributes” 当我们尝试将 children 道具传递给不带任何道具的组件时发生。 要解决错误,需要定义并键入组件上的属性。

下面是错误发生方式的示例。

const Box = () => { // 不带属性
  return (
    <div>
      <p>Hello world</p>
    </div>
  );
};

const App = () => {
  return (
    <div className="App">
      {/* ⛔️ Error: Type '{ children: Element; }' has no properties
       in common with type 'IntrinsicAttributes'. ts(2559) */}
      <Box>
        <span>Test</span>
      </Box>
    </div>
  );
};

export default App;

请注意, Box 组件不使用任何属性,但我们正在尝试将 children 属性传递给它。

当一个组件与一个开始和结束标签一起使用时,标签之间的所有内容都会作为 children 属性传递给组件。

<MyComponent>
  Some children here
</MyComponent>

解决错误的一种方法是,如果不需要带任何子组件,则将组件用作 <Box />

const Box = () => {
  return (
    <div>
      <p>Hello world</p>
    </div>
  );
};

const App = () => {
  return (
    <div className="App">
      <Box />
    </div>
  );
};

export default App;

这样就可以解决错误了,因为没有传递任何子属性。

但是,如果我们的组件必须采用 children 属性,则在声明组件时必须传入它。

import React from 'react';

type BoxProps = {
  children: React.ReactNode; // ?️ type children
};

const Box = (props: BoxProps) => {
  return <div>{props.children}</div>;
};

const App = () => {
  return (
    <div className="App">
      <Box>
        <span>Hello</span>
        <span>Test</span>
      </Box>
    </div>
  );
};

export default App;

我们在 Box 组件上定义并键入了一个 children 属性来解决错误。

现在可以将 Box 组件传递给子组件并渲染它们。

确保我们的组件定义了它必须采用的所有属性。

如果您不想显式键入 props 并且只想关闭类型检查,则可以将 props 对象设置为 any 类型。

const Box = (props: any) => { // 关闭 props 的类型检查
  return <div>{props.children}</div>;
};

const App = () => {
  return (
    <div className="App">
      <Box>
        <span>Hello</span>
        <span>Test</span>
      </Box>
    </div>
  );
};

export default App;

每当我们将组件用作:

<MyComponent>
  Some children
</MyComponent>

你必须在特定组件上定义并键入 children 属性。

import React from 'react';

type BoxProps = {
  children: React.ReactNode; // ?️ 定义 children 属性
};

const Box = (props: BoxProps) => {
  return <div>{props.children}</div>;
};

const App = () => {
  return (
    <div className="App">
      <Box>
        <span>Hello</span>
        <span>Test</span>
      </Box>
    </div>
  );
};

export default App;

如果我们不需要将任何子组件传递给我们的组件,只需将该组件用作 <MyComponent />

const Box = () => {
  return <div>Hello world</div>;
};

const App = () => {
  return (
    <div className="App">
      <Box />
    </div>
  );
};

export default App;