【问题标题】:How to define props in Typescript when a parent component injects props in its children?当父组件在其子组件中注入道具时,如何在 Typescript 中定义道具?
【发布时间】:2019-02-24 15:09:23
【问题描述】:

当一个组件克隆它的children注入props时,如何定义children的props类型?

我收到一个错误,原因是 injectedProps 应该在 Child

const Parent: React.SFC<ParentProps> = ({ children }) => (
  <div>
    {React.cloneElement(children[0], { injectedProp: 'foo' })}
  </div>
);

const Child: React.SFC<ChildProps> = ({ injectedProp }) => (
  <div attr={injectedProp} />
);

type ChildProps = {
  injectedProp: string;
};

<Parent>
  <Child />
</Parent>

子错误:injectedProp 丢失

【问题讨论】:

  • injectedProp 不包括在ChildProps
  • 我忘了编辑 SO 的类型:p
  • 使其可选或提供默认参数值

标签: reactjs typescript tslint react-tsx


【解决方案1】:

这个 Code Pattern 不能在 TypeScript 中正确输入,如果你问我,这很难看。相反,请考虑传递一个函数,该函数接受注入的 prop 并创建最终的孩子:

interface ParentProps {
  children: (childProps: ChildProps) => React.ReactNode;
}

const Parent: React.SFC<ParentProps> = ({ children }) => (
  <div>
    {children({ injectedProp: 'foo' })}
  </div>
);

const Child: React.SFC<ChildProps> = ({ injectedProp }) => (
  <div title={injectedProp} />
);

type ChildProps = {
  injectedProp: string;
};

function foo() {
  return <Parent>
    {childProps => <Child {...childProps} />}
  </Parent>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2020-08-04
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多