我有以下方法返回一个Component
const getChildComponent = ({ type }) => {
let childComponent = null
switch (type) {
case 'component_1':
childComponent = <SomeComponent />
break;
}
return { childComponent }
}
export default getChildComponent
我从下面的单独组件调用上述方法
export default class ParentComponent extends React.Component {
render() {
const { component } = getChildComponent({ type })
return (
<Container>
<Content>
{childComponent} // How to pass props here?
</Content>
</Container>
);
}
}
是否可以将道具从ParentComponent
传递到childComponent
(而不必通过getChildComponent()
方法传递道具)?
答案 0 :(得分:3)
返回the component, not the element。换句话说,返回SomeComponent
,而不是<SomeComponent/>
:
const getChildComponent = ({ type }) => {
switch (type) {
case 'component_1':
return SomeComponent;
}
}
export default class ParentComponent extends React.Component {
render() {
const ChildComponent = getChildComponent({ type });
return (
<Container>
<Content>
<ChildComponent {...props}/>
</Content>
</Container>
);
}
}
答案 1 :(得分:1)
由于您的getChildComponent
函数返回一个React元素而不是实际组件,因此您应该能够使用React.cloneElement将自定义道具传递给子组件。
以下是使用您提供的代码示例的示例。
export default class ParentComponent extends React.Component {
render() {
const { component } = getChildComponent({ type })
return (
<Container>
<Content>
{React.cloneElement(component, { propA: "foobar" })} // pass props to second argument
</Content>
</Container>
);
}
}