簡體   English   中英

如何在嵌套子進程中進行迭代?

[英]How to iterate in nested children with react?

我有一個簡單的Form組件循環遍歷其子項並搜索名稱為“ FormField ”的任何子項,然后將事件處理程序附加到這些子項。

export default class Form extends React.Component {
  componentWillMount() {
    this.fields = {}
  }
  handleFieldChange(name, value) {
    const newFields = {...this.fields}
    newFields[name] = value;

    this.props.onChange(newFields)
  }
  render() {
    this.children = React.Children.map(this.props.children, (child, index) => {
      if (child.type.name == 'FormField') {
        this.fields[child.props.name] = child.props.data;
        return React.cloneElement(child, {
          onChange: this.handleFieldChange.bind(this, child.props.name)
        })
      }
      return child
    })
    return (
      <div className="form">{this.children}</div>
    )
  }
}

這使我能夠這樣做:

<Form onChange={this.handleFormChange.bind(this)}>
  <FormField label="Title" name="title" data={item.title} validators={[required]}>
    <TextInput placeholder="Example"></TextInput>
  </FormField>
</Form>

但不是這個(注意div):

<Form onChange={this.handleFormChange.bind(this)}>
  <div>
    <FormField label="Title" name="title" data={item.title} validators={[required]}>
      <TextInput placeholder="Example"></TextInput>
    </FormField>
  </div>
</Form>

這給我一個FormField組件中的錯誤

未捕獲的TypeError:this.props.onChange不是函數

我希望能夠在我的Form組件中放置div(可能還有嵌套的div等),並且仍然可以找到FormField組件,這樣我就可以用css布局我的表單和輸入。

我怎樣才能做到這一點?

編輯:我嘗試過遞歸迭代,但是我得到了堆棧溢出。

// FIXME: Won't work because of recursion error
function traverseChildren(children, self) {
  return React.Children.map(self.props.children, (child, index) => {
    if (child.type.name == 'FormField') {
      self.fields[child.props.name] = child.props.data;
      return React.cloneElement(child, {
        onChange: self.handleFieldChange.bind(self, child.props.name)
      })
    } else {
      if (child.props.children) {
        return traverseChildren(child.props.children, self)
      }
      return child
    }
  })
}

我認為這是查看react的context的好例子。

在您的情況下,父級可以將onChange方法放在子級將能夠調用的上下文中。

可以在這里找到一個相對簡短且有希望的有用的示例

RadioGroup建立了Radio能夠使用的上下文。 無論Radio放在多么深的地方。

添加新div時,需要從this.props.children.children獲取表單字段

為了使它適用於任何深度的FormFields,你必須遞歸遍歷孩子克隆你感興趣的節點放入你將創建的新子數組中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM