【问题标题】:FragmentContainer vs just another React component as a wrapper?FragmentContainer 与仅作为包装器的另一个 React 组件?
【发布时间】:2020-02-18 12:36:06
【问题描述】:

我正在编写代码以将现有的 React 组件插入到另一个组件中。

最初在代码中完成的方式是使用片段容器。 我知道 fragmentContainer 是一个高阶组件,它充当包装器,并返回另一个 React 组件。 但是,我试图了解我是否真的需要使用 fragmentContainer 来插入我现有的组件,或者我可以创建另一个包装器组件。

是否有确定的方法来确定在 React 组件中应该在哪里使用 fragmentContainer 和 React 组件?

我查看了官方文档(https://relay.dev/docs/en/fragment-container) 和其他资源,但似乎任何一种方式都可以使用? 是否存在应该使用片段容器的特殊情况?

【问题讨论】:

    标签: reactjs graphql relay


    【解决方案1】:

    您使用 fragmentContainer 来确保组件中需要哪些数据。

    例如:

    父.js

    const ParentComponent = ({list}) => (
       <QueryRenderer
          query={graphql`
             query List {
                id
                ...childComponent_item
             }
          `}
          render={
             list.map(item => (
                <ChildComponent item={item} key={item.id} />
             ))
          }
       />
    );
    export default ParentComponent;
    // Here, in  the parent component
    // I need the id of each item of the list but I don't need the others values.
    

    childComponent.js

    const ChildComponent = item => (
       <>
          <div>{item.name}</div>
          <div>{item.avatar}</div>
          <div>{item.othervalue}</div>
       </>
    )
    const ChildComponentWithFragment = createFragmdentContainer(
       ChildComponent, 
       {
          list: graphql`
             fragment childComponent_item on ItemType {
                name
                avatar
                othervalue
             }
          `
       };
    export default ChildComponentWithFragment;
    // Here in the child component
    // I need the others data of the Item object so i have to get these values
    // in my fragment
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2020-10-23
      • 2020-08-29
      • 2021-08-29
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      相关资源
      最近更新 更多