Reactjs 当父组件在其子组件中注入道具时,如何在Typescript中定义道具?
当组件克隆其子组件以向其中注入道具时,如何定义子组件道具类型 我收到一个错误原因Reactjs 当父组件在其子组件中注入道具时,如何在Typescript中定义道具?,reactjs,typescript,tslint,react-tsx,Reactjs,Typescript,Tslint,React Tsx,当组件克隆其子组件以向其中注入道具时,如何定义子组件道具类型 我收到一个错误原因injectedProps应在Child const Parent: React.SFC<ParentProps> = ({ children }) => ( <div> {React.cloneElement(children[0], { injectedProp: 'foo' })} </div> ); const Child: React.SFC<
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;
};
const-Parent:React.SFC=({children})=>(
{React.cloneElement(子项[0],{injectedProp:'foo'})}
);
const Child:React.SFC=({injectedProp})=>(
);
类型ChildProps={
injectedProp:string;
};
子项中的错误:injectedProp
缺失
这个代码模式不能在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>
}
interface ParentProps{
子级:(childProps:childProps)=>React.ReactNode;
}
const Parent:React.SFC=({children})=>(
{children({injectedProp:'foo'})}
);
const Child:React.SFC=({injectedProp})=>(
);
类型ChildProps={
injectedProp:string;
};
函数foo(){
返回
{childProps=>}
}
injectedProp
未包含在ChildProps
中我忘记编辑SO:p的类型,请将其设置为可选或提供默认参数值
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>
}