【问题标题】:How to iterate children in React using render props如何使用渲染道具在 React 中迭代子级
【发布时间】:2019-07-24 16:38:21
【问题描述】:

我的表单有这个伪代码。我想只显示 canAccess=true 的字段。

const initialValues = {
  firstName: { canAccess: true, value: 'Mary' },
  surName: { canAccess: false, value: 'Casablanca' }  
}

<Form initialValues={initialValues}>
{props => 
  <>
    <div className="nestedItem">
      <Field name="firstName" />
    </div>
    <Field name="surName" />
  </>
}
</Form>

使用此代码,我希望看到仅显示带有 firstName 的字段。

我知道我可以通过 React.Children.map() 进行迭代,但我不知道在使用渲染道具时如何迭代孩子。 也可以有嵌套元素,所以我想按名称查找特定类型的组件。

感谢您的帮助。

【问题讨论】:

  • 把孩子们从道具里拿走。
  • 不确定你的意思。在表单中我做了 React.Chidlren.map(chidren, x => x) 我有 []

标签: reactjs


【解决方案1】:
const initialValues = {
  firstName: { canAccess: true, value: 'Mary' },
  surName: { canAccess: false, value: 'Casablanca' }  
}

<Form initialValues={initialValues}>
{props => 
  <>
    {
      Object.keys(props.initialValues).map(k => (
        k.canAccess && <Field name={k} />
      ));
    }
  </>
}
</Form>

编辑:您的表单可以执行一些逻辑并将过滤后的项目传递回您的组件。

getFilteredItems = items => Object.keys(items).reduce((acc, key) => {
  const item = items[key];
  const { canAccess } = item;
  if(!canAccess) return acc;
  return {
    ...acc,
    [key]: item
  }
}, {}));

render() {
  const { initialValues, children } = this.props;
  const filteredItems = this.getFilteredItems(initialValues);
  return children(filteredItems);
}

<Form initialValues={initialValues}>
  { props => 
    <>
      { 
        Object.keys(props).map(k => <Field name={k} />) 
      }
    </>
</Form>

【讨论】:

  • 这是一种方法,但我不喜欢它,因为我必须在每一个使用 Form 的地方都这样做。我必须在“内部”
    组件中进行操作。
  • 您的回答帮助我找到了我正在寻找的解决方案。我将其粘贴为单独的答案,因为在这里我无法格式化代码。谢谢
【解决方案2】:

这就是我要找的。​​p>

const Form = ({initialValues, children}) =>
  props => 
    <Authorized initialValues={initialValues}>
      {typeof children === 'function' ? children(props) : children}
    </Authorized>
const Authorized = ({initialValues, children}) => {
  // Do check 
  React.Children.map(chidlren, x => { 
  if(x.type === Field ) // && initialValues contains x.props.name
    return x

  return null
  ... })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2017-03-06
    • 2018-09-02
    • 2022-06-15
    相关资源
    最近更新 更多