2017-12-24 12 views
0

Reactに子に関数を渡すことに問題があります。このような機能をthisにバインドするか、またはarrowの機能を使用することについては、stackoverflowの複数のスレッドを読んでいますが、それでも解決できません。基本的に私はd3.select().datum()datumと呼ばれる関数を渡す必要がある:d3.select(ノード) .datum(this.props.datum) は.call(チャート)上記のコードでReact:機能していない子に関数を渡す

class BarChart extends React.Component { 
    constructor(props){ 
    super(props) 
    this.createBarChart = this.createBarChart.bind(this) 
    } 

    componentDidMount() { 
    this.createBarChart() 
    } 

    componentDidUpdate() { 
    this.createBarChart() 
    } 

    createBarChart() { 
    console.log("In createBarChart: " + this.props.datum); 
    const node = this.node 
    nv.addGraph(function() { 
     var chart = nv.models.discreteBarChart() 
     .x(function(d) { return d.label }) 
     .y(function(d) { return d.value }) 
     .staggerLabels(true) 
     //.staggerLabels(historicalBarChart[0].values.length > 8) 
     .showValues(true) 
     .duration(250) 
     ; 
    d3.select(node) 
     .datum(this.props.datum) 
     .call(chart); 
    nv.utils.windowResize(chart.update); 
    return chart; 
}); 
    } 

    render() { 
    return <svg ref={node => this.node = node} 
     width={1000} height={500}> 
    </svg> 
    } 

} 

module.exports = BarChart; 

import datum from './datum' 

class App extends React.Component { 
    render() { 
    return (
     <DefaultLayout title={this.props.title}> 
     <div>Hello {this.props.name}</div> 
     <div className='App'> 
      <BarChart datum = { datum.bind(this) }/> 
     </div> 
     </DefaultLayout> 
    ); 
    } 
} 

module.exports = App; 

私は<BarChart datum = {() => this.datum() }/>が、運を行うことを試みた:は、私は次のようにBarChartコンポーネントにdatum関数を渡すしようとしています

TypeError: this.props is undefined

原因となります。任意の提案は

var datum = function datumFunc() { 
    return [ 
    { 
     key: "Cumulative Return", 
     values: [ 
     ... 
     ] 
    } 
    ] 
} 

export default datum 

ます:datum.jsからモジュールがそのように見えるように私は、インポートしています

constructor(props){ 
    super(props) 
    this.createBarChart = this.createBarChart.bind(this) 
    this.props.datum = this.props.datum.bind(this) 
} 

datum機能:その後もcreateBarChart機能と同様にBarChartコンポーネントのconstructordatum機能を結合します大変感謝します。

答えて

1

nv.addGraphに渡す匿名関数はバインドされていないため、thisは、その関数が呼び出されたときに有効範囲外です。

nv.addGraph(function() { 
    var chart = nv.models.discreteBarChart() 
    .x(function(d) { return d.label }) 
    .y(function(d) { return d.value }) 
    .staggerLabels(true) 
    //.staggerLabels(historicalBarChart[0].values.length > 8) 
    .showValues(true) 
    .duration(250) 
    ; 
    d3.select(node) 
    .datum(this.props.datum) 
    .call(chart); 
    nv.utils.windowResize(chart.update); 
    return chart; 
}.bind(this)); 
//^^^^^^^^^^ would fix it 

また、あなたがすでにcreateBarChartで行っているとして、その関数に名前を付け、コンストラクタで、それを結合することができます。

関連する問題