首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何键入一个父组件的子组件,该组件的道具已动态添加到?

如何键入一个父组件的子组件,该组件的道具已动态添加到?
EN

Stack Overflow用户
提问于 2019-05-15 09:39:09
回答 2查看 197关注 0票数 2

我有两个组件--一个是子组件,另一个是父组件。父组件被设计为一个临时组件,它对数据进行ajax调用,然后将数据向下传递给其子组件。它传递给子对象的道具是通过带有this.props.childrenReact.CloneElement动态添加的。

关于流,它不能解释/看到我在重新克隆时添加的额外道具。

我怎么才能克服这个问题呢?

这两个组件是如何关联的。

代码语言:javascript
复制
<ParentComponent>
     </ChildComponent />
</ParentComponent>
代码语言:javascript
复制
const ParentComponent = (props) => {
     // code
     return (
          <>
               {React.cloneElement(this.props.children, { extraProps }}
          <>
      );
}
代码语言:javascript
复制
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`
}
EN

回答 2

Stack Overflow用户

发布于 2019-05-15 20:03:16

到目前为止,我还没有找到让它完全工作的好方法。这里有一些代码可以将其设置为正确的方向。

代码语言:javascript
复制
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>

Flow Try

票数 0
EN

Stack Overflow用户

发布于 2019-05-16 22:50:22

Flow有一些great documentation on typing higher-order components。它稍微改变了你的实现,但我认为它应该能达到和你的代码一样的效果。使用文档的example for injecting props,您可以编写

代码语言:javascript
复制
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>
  );
}

Try Flow

现在injectY属性是通用的,所以您可以在可能使用React.cloneElement的其他地方重用该模式。我不熟悉React.cloneElement,所以除了使用injectY可能会得到更好的类型检查外,我不能说太多关于克隆和特殊方法之间的区别。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56140703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档