React:将函数传递给不工作的孩子

问题描述 投票:0回答:1

我在React将一个函数传递给孩子时遇到了麻烦。我在stackoverflow上阅读了多个线程,讨论将这些函数绑定到this或使用arrow函数,但仍然无法解决它。基本上我需要将名为datum的函数传递给d3.select().datum()

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; 

在上面的代码中,d3.select(node).datum(this.props.datum).call(chart);原因

TypeError:this.props未定义

我试图通过以下方式将datum函数传递给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() }/>但没有运气。然后还与datum函数类似地在constructor组件的BarChart中绑定createBarChart函数:

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

我从datum作为模块导入的datum.js函数看起来像这样:

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

export default datum

任何建议将不胜感激。

reactjs d3.js nvd3.js
1个回答
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一样。

© www.soinside.com 2019 - 2024. All rights reserved.