我有两个组件--一个是子组件,另一个是父组件。父组件被设计为一个临时组件,它对数据进行ajax调用,然后将数据向下传递给其子组件。它传递给子对象的道具是通过带有this.props.children的React.CloneElement动态添加的。
关于流,它不能解释/看到我在重新克隆时添加的额外道具。
我怎么才能克服这个问题呢?
这两个组件是如何关联的。
<ParentComponent>
</ChildComponent />
</ParentComponent>const ParentComponent = (props) => {
// code
return (
<>
{React.cloneElement(this.props.children, { extraProps }}
<>
);
}type PropTypes = {
extraProps: string, // flow complains, and I don't know how to get it to recognize that the extraProps is added dynamically.
};
const ChildComponent = (props) => {
// code that uses the additional `extraProps`
}发布于 2019-05-15 20:03:16
到目前为止,我还没有找到让它完全工作的好方法。这里有一些代码可以将其设置为正确的方向。
import * as React from 'react'
const ParentComponent = (props: { children: React.Element<typeof ChildComponent> }) => {
return (React.cloneElement(props.children, { extraProps: 'hello' }));
// return (React.cloneElement(props.children, { extraProps: 1 })); // <-- this will error
}
type PropTypes = {
extraProps?: string, // not great because you'll still have to check presence, but at least it provides
// type checking on extraProps in the ParentComponent
};
const ChildComponent = (props: PropTypes) => {
return <p>{props.extraProps}</p>
}
<ParentComponent><ChildComponent /></ParentComponent>发布于 2019-05-16 22:50:22
Flow有一些great documentation on typing higher-order components。它稍微改变了你的实现,但我认为它应该能达到和你的代码一样的效果。使用文档的example for injecting props,您可以编写
import * as React from 'react';
type Props = {
x: string,
y: string,
}
function injectY<Config: {}>(
Component: React.AbstractComponent<Config>
): React.AbstractComponent<$Diff<Config, { y: string | void }>> {
return function WrapperComponent(
props: $Diff<Config, { y: string | void }>
) {
return <Component {...props} y="injected" />;
}
}
function Child({ x, y }: Props) {
return x + y;
}
const EnhancedChild = injectY(Child);
function App() {
return (
<div>
<Child x="explicit" y="explicit" />
<EnhancedChild x="explicit" />
</div>
);
}现在injectY属性是通用的,所以您可以在可能使用React.cloneElement的其他地方重用该模式。我不熟悉React.cloneElement,所以除了使用injectY可能会得到更好的类型检查外,我不能说太多关于克隆和特殊方法之间的区别。
https://stackoverflow.com/questions/56140703
复制相似问题