【问题标题】:Adding required props to child react elements with typescript使用打字稿向子反应元素添加所需的道具
【发布时间】:2020-11-23 11:20:28
【问题描述】:

我想定义一个父元素,我需要在其中传递一些反应元素作为道具。我想对子组件的道具添加一些要求,但我无法让我的打字稿完全按预期工作。这是一个最小的例子

import * as React from "react";

function JSXElementChild() {
  return <div>Child One</div>;
}

const ReactFCChild: React.FC<{ label: string }> = ({ label }) => {
  return <div>{label}</div>;
};

function Parent({
  children
}: {
  children: React.ReactElement<{ label: string }>[];
}) {
  return (
    <div>
      {children.map((child) => (
        <div key={child.props.label}>{child}</div>
      ))}
    </div>
  );
}

export default function App() {
  return <Parent children={[<JSXElementChild />, <ReactFCChild />]} />;
}

Parent 组件需要 children 作为道具,而这些子组件需要 label: string 作为道具。现在上面确实正确标记了ReactFCChild 的打字稿问题; Property 'label' is missing in type '{}' but required in type '{ label: string; }'.ts(2741)。但是JSXElementChild 不会产生任何问题。如何解决?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    完全更新的答案。 请记住,你应该明确输入React.FC,并且你不应该使用JSX作为根组件

    import * as React from "react";
    
    
    const JSXElementChild: React.FC = () => {
        return <div>Child One</div>;
    }
    
    const ReactFCChild: React.FC<{ label: string }> = ({ label }) => {
        return <div>{label}</div>;
    };
    
    function Parent({
        children
    }: {
        children: React.ReactElement<{ label: string }>[];
    }) {
        return (
            <div>
                {children.map((child) => (
                    <div key={child.props.label}>{child}</div>
                ))}
            </div>
        );
    }
    
    function App() {
        return React.createElement(Parent, {
            children: [
                React.createElement(JSXElementChild, null), //  error
                React.createElement(ReactFCChild, { label: 'd' }) // no error
            ]
        });
    }
    
    function App2() {
        return React.createElement(Parent, {
            children: [
                /**
                 * still error, because JSXElementChild don't expect {label: string}
                 * If you add typings for JSXElementChild, error will disappear
                 */
                React.createElement(JSXElementChild, { label: 'd' }), //error
                React.createElement(ReactFCChild, { label: 'd' }) // no error
            ]
        });
    }
    

    【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2020-08-21
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2020-12-26
    • 2021-05-10
    相关资源
    最近更新 更多