ค้นหาเว็บไซต์

reactjs - ได้รับข้อผิดพลาดเมื่อใช้ type "React.ReactNode" กับ children ควรใช้ type ไหน?


ได้รับข้อความแสดงข้อผิดพลาดเมื่อใช้ฟังก์ชัน LoaderIndicator() ซึ่งแสดงผล children เมื่อ loading=false ดูโค้ดด้านล่าง ข้อผิดพลาดเกิดขึ้นเมื่อฉันใช้ React.ReactNode แทนการใช้ประเภท any แต่โดยปกติฉันจะใช้ React.ReactNode เป็นประเภทของ children ข้อผิดพลาดที่ฉันได้รับคือ:

'LoaderIndicator' cannot be used as a JSX component. Its return type '{}' is not a valid JSX element. Type '{}' is missing the following properties from type 'Element': type, props, key. ts(2786)

ฉันไม่รู้ว่าจะซ่อมข้อผิดพลาดนี้อย่างไร ฉันได้ลองเกือบทุกอย่างแล้ว มีใครสามารถช่วยได้ไหม? :)

export type LoaderIndicatorProps = {
  loading: boolean;
  children?: React.ReactNode; 
};
export function LoaderIndicator(props: LoaderIndicatorProps) {
  const { loading, children } = props;

  if (loading) {
    return (
      <div>
        <Container>
          <Icon />
          <h3 style={{ color: "#ffffff" }}>Wait for a moment...</h3>
        </Container>
      </div>
    );
  } else {
    return children;
  }
}

คำตอบ #1

คอมโพเนนต์ของ React ควรส่งกลับ JSX.Element อย่างที่คุณเห็น ลูกของคุณมีประเภทเป็น React.ReactNode ดังนั้นการส่งกลับตรงๆ จะไม่ทำงาน คุณจำเป็นต้องห่อพวกมันไว้ภายใน element หรือ React.Fragment:

type TestComponentProps = {
    children?: React.ReactNode;
}

function TestComponent(props: TestComponentProps) {
    return <React.Fragment>{props.children}</React.Fragment>;
}

บทความที่เกี่ยวข้อง