当父组件在其子代中注入道具时,如何在Typescript中定义道具?

时间:2018-09-20 10:21:47

标签: reactjs typescript tslint react-tsx

当组件克隆其子代以向其注入道具时,如何定义子代道具类型?

我收到一个错误原因,interface: ge-2/0/0 description: "site1;;hostname1;ge-16/0/9;;;TRUST;"; port mode: trunk interface: ge-2/0/2 description: "site2;;hostname2;ge-16/0/8;;;TRUST;"; port mode: trunk 中应该有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> 丢失

1 个答案:

答案 0 :(得分:0)

无法在TypeScript中正确键入此代码模式,如果您问我,该代码模式很难看。相反,请考虑传递一个采用注入的道具并创建最终子代的函数:

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>
}