[英]React: Adding props only to React component and not html tag (React.Children.map recursively)
I have a Form
's React component that manage several Field
's component and attach to them some props.我有一个
Form
的 React 组件,它管理多个Field
的组件并将一些道具附加到它们上。 Until now, I created only simple form, like this到现在为止,我只创建了简单的表单,就像这样
<Form>
<FieldText/>
<FieldDropdown />
</Form>
but now, I need a form with more complex structure, like this但现在,我需要一个结构更复杂的表格,像这样
<Form>
<div>
<a data-tab="first">First Tab</a>
<a data-tab="second">Second Tab</a>
</div>
<div data-tab="first">
<FieldText />
</div>
<div data-tab="second">
<FieldText />
</div>
</Form>
With simple form I added props to Field
in this way通过简单的形式,我以这种方式向
Field
添加了道具
var Form = React.createClass({
render: function(){
<form onSubmit={this.submit} acceptCharset="UTF-8" ref={cForm.id}>
{
React.Children.map(this.props.children, child => {
// if type is funtion the is a react component
if( typeof child.type === "function"){
return React.cloneElement(child, {
attachToForm: this.attachToForm,
disabled: this.props.disabled
});
} else {
return child;
}
})
}
</form>
}
});
How can I modify Form
to add some props only to Field
's component and not html tag?如何修改
Form
以仅将一些道具添加到Field
的组件而不是 html 标签?
Each child component should have a type
field, for normal html elements, this would be a string such as "span", "div", etc.每个子组件都应该有一个
type
字段,对于普通的 html 元素,这将是一个字符串,例如“span”、“div”等。
You can simply switch
(or your conditional of choice) against that field.您可以简单地针对该字段
switch
(或您选择的条件)。
Simple abstracted version would be like:简单的抽象版本如下:
const Foo = (props) => (
<div style={props.style}>FOO</div>
);
class App extends React.Component {
render () {
return (
<div>
{ React.Children.map(this.props.children, child => {
if(typeof child.type === 'string') {
switch(child.type) {
case 'span':
return React.cloneElement(child, { style: { background: 'pink' }});
case 'div':
return React.cloneElement(child, { style: { background: 'red' }});
}
} else {
switch(child.type.name) {
case 'Foo':
return React.cloneElement(child, { style: { background: 'blue' }});
}
}
return child;
})}
</div>
);
}
}
ReactDOM.render(
<App>
<span>span</span>
<p>p</p>
<Foo />
<div>div</div>
</App>,
document.getElementById('root')
);
With codepen:使用代码笔:
http://codepen.io/cjke/pen/qRQvmY?editors=0010 http://codepen.io/cjke/pen/qRQvmY?editors=0010
EDIT Based on the comments, the question is more about recursively walking the DOM tree - in which, its simple a duplicate of this question: React.Children.map recursively?编辑根据评论,问题更多是关于递归地遍历 DOM 树 - 其中,它是这个问题的简单重复: React.Children.map recursively?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.