2015-04-03 61 views
1

我不知道這是一個錯誤還是如何解決這個問題,但我注意到React.addons.cloneWithProps可以與標準標記(如<div>)一起使用,但不適用於組件的子項。反應:爲什麼React.addons.cloneWithProps不能用於組件?

這是一個問題的工作示例。我期望這兩個div都有一個紅色的背景,但是用組件創建的那個不是。

http://jsfiddle.net/ydpk2dp7/1/

var Main = React.createClass({ 
    render: function() {  
     children = React.Children.map(this.props.children, function (c, index) { 
      return React.addons.cloneWithProps(c, { 
       style: { 
        background: 'red' 
       } 
      }); 
     }); 

     return (
      <div> 
       {children} 
      </div> 
     ); 
    },  
}); 

var Comp = React.createClass({ 
    render: function() {  
      return (
       <div>{this.props.children}</div> 
     ); 
    } 
}); 


React.render(
    <Main> 
     <div>1</div> 
     <Comp>2</Comp> 
    </Main> 
    , document.body); 

回答

2

我不知道這是否是一個錯誤或沒有,但我想包中不屬於母公司所擁有的部分家長的反應的組分。以下提供了一個工作結果。

var Main = React.createClass({ 
    render: function() {  
     children = React.Children.map(this.props.children, function (c, index) { 
      return React.addons.cloneWithProps(c, {style: {background: 'red'}}); 
     }); 

     return (
      <div> 
       {children} 
      </div> 
     ); 
    },  
}); 

var Comp = React.createClass({ 
    render: function() {  
      return (
       <div>{this.props.children}</div> 
     ); 
    } 
}); 


React.render(
    <Main> 
     <div> 
      <Comp>2</Comp> 
      <Comp>3</Comp> 
      <Comp>4</Comp> 
     </div> 
    </Main> 
    , document.body) 
2

晚會晚了,但我想我會幫助誰看到這在未來。

的問題是你丟棄style道具在Comp

var Comp = React.createClass({ 
    render: function() { 
      var style = this.props.style; // you weren't passing this to the <div> below 
      return (
       <div style={style}>{this.props.children}</div> 
     ); 
    } 
}); 

這也可能是最好的解壓你props需要什麼,通上休息。與ES2015的destructuring spread operator容易實現:

var Comp = React.createClass({ 
    render: function() { 
      var { children, ...props } = this.props; 
      return (
       <div {...props}>{ children }</div> 
     ); 
    } 
}); 

這將允許您的組件,在最初寫作,你沒有想到的指定道具。

現在,例如,現在您可以添加一個onClick處理程序,並期望它的工作:

<Comp onClick={this.onClick} /> 

記住,只有props的「DOM」元素具有特殊的意義。對於自定義元素,它們只是常規屬性,供您隨意解釋。

相關問題