【发布时间】:2017-12-24 01:35:33
【问题描述】:
我无法将函数传递给 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() }/>,但没有运气。然后也在BarChart组件的constructor中绑定datum函数,类似于createBarChart函数:
constructor(props){
super(props)
this.createBarChart = this.createBarChart.bind(this)
this.props.datum = this.props.datum.bind(this)
}
我作为模块从datum.js 导入的datum 函数如下所示:
var datum = function datumFunc() {
return [
{
key: "Cumulative Return",
values: [
...
]
}
]
}
export default datum
任何建议将不胜感激。
【问题讨论】: