2015-10-05 99 views
1

我有这些阵营类阵营渲染方法不要求嵌套的组件

class App extends React.Component { 

    constructor(props) { 
     super(props); 
    } 

    componentDidMount() { 
     const { dispatch } = this.props; 
     var props = this.props; 
     dispatch(fetchDistricts('California')); 
    } 

    render() { 
     return (
      <div class="app"> 
       <Chart width={this.props.width} 
        height={this.props.height}> 
       <Bar data={this.props} 
        width={this.props.width} 
        height={this.props.height}> 
       </Bar> 
       </Chart> 
      </div> 
     ); 
    } 
}; 

图表看起来像这样

export default class Chart extends React.Component { 
    render() { 
     return (
      <svg width={this.props.width} 
       height={this.props.height}> 
      </svg> 
     ); 
    } 
}; 

和酒吧看起来像这样

export default class Bar extends React.Component { 
    shouldComponentUpdate(nextProps) { 
     debugger 
     return this.props.data !== nextProps.data; 
    } 

    render() { 
     debugger 
     let props = this.props; 
     let data = props.data.map((d) => 
      { 
       return d.y; 
      } 
     ); 

     let yScale = d3.scale.linear() 
      .domain([0, d3.max(data)]) 
      .range([0, this.props.height]); 

     let xScale = d3.scale.ordinal() 
      .domain(d3.range(this.props.data.length)) 
      .rangeRoundBands([0, this.props.width], 0.05); 
     let bars = data.map((point, i) => { 
      var height = yScale(point), 
      y = props.height - height, 
      width = xScale.rangeBand(), 
      x = xScale(i); 

      return (
       <Rect height={height} 
        width={width} 
        x={x} 
        y={y} 
        key={i}> 
       </Rect> 
      ); 
     }); 

    return (
     <g>{bars}</g> 
    ); 
    } 
}; 

在酒吧调试器没有被调用 - 渲染方法没有被调用。

为什么?

回答

2

只有顶层组件实际上呈现在渲染方法中。当您将Bar组件放入Chart组件中时,实际上只是将Bar作为Chart的属性传递。

React允许您以图表组件的this.props.children的身份访问它。所以,你的图表组件的渲染方法应该是...

render() { 
    return (
     <svg> 
      {this.props.children} 
     </svg> 
    ) 
} 

延伸阅读:https://facebook.github.io/react/docs/multiple-components.html