2017-02-11 34 views
2

我有一个Form的React组件管理多个Field的组件,并附加一些道具。 到现在为止,我只创建简单的表格,这样React:将道具只添加到React组件而不是html标签(React.Children.map递归)

<Form> 
    <FieldText/> 
    <FieldDropdown /> 
</Form> 

,但现在,我需要更复杂的结构形式,这样

<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> 

用简单的形式我在这添加道具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> 
    } 

}); 

如何修改Form添加一些道具只有Field的组件,而不是 html标记?

回答

1

每个子组件应该有一个type场,对于正常的html元素,这将是一个字符串,如“跨越”,“格”,等等。

你可以简单地switch(或您的条件选择)反对那个领域。

简单抽象的版本是这样的:

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') 
); 

随着codepen:

http://codepen.io/cjke/pen/qRQvmY?editors=0010

编辑 根据该意见,问题更多的是递归遍历DOM树 - 其中,其简单的这个问题的副本:React.Children.map recursively?

+0

我知道,实际上我用'child.type'来确定孩子是否是一个函数。我无法弄清楚如何创建一个递归方法来添加内部表单html标签,并添加新的道具只有字段组件(如果字段是在另一个html标签内) – Webman

+0

如果“你知道”,那么你需要重新考虑你的问题的措辞 - 最后一行问我怎么能说出一个组件和一个html元素之间的区别。它没有提到关于递归地走下DOM树的内容。 – Chris

+0

对不起,但我的英语不好,所以我更难解释自己。在你的例子中,如果你把'Foo'放在最后一个div中,'Foo'将会是红色而不是蓝色。这是我的问题 – Webman

相关问题