![](/img/trans.png)
[英]How to iterate through nested children of an object and collect an array of names
[英]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
}
})
}
添加新div時,需要從this.props.children.children
獲取表單字段
為了使它適用於任何深度的FormFields,你必須遞歸遍歷孩子克隆你感興趣的節點放入你將創建的新子數組中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.