我有一个自定义nvd3
scatterChart
图的工具提示的函数。在我想要更新状态的函数中,所以我调用另一个执行setState
的函数:
chart.tooltip.contentGenerator(function (d) {
var html = "<div>";
d.series.forEach(function(elem){
Object.keys(data_obj).forEach(function(key_1) {
var outer_obj = data_obj[key_1];
if (outer_obj["key"] === elem.key) {
// THIS FUNCTION UPDATES STATE
this.showBarChart(elem.key);
var expr = outer_obj["values"][0]["expr"];
html += "<p>" + elem.key + "</p>";
html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";
}
});
})
html += "</div>";
return html;
}).bind(this);
我在构造函数中有:
class ScatterChart extends React.Component {
constructor(props){
super(props);
this.createScatterChart = this.createScatterChart.bind(this);
this.showBarChart = this.showBarChart.bind(this);
this.state = {
neuron_name: ""
}
}
render
:
render() {
console.log(this.state.neuron_name);
return <div width={500} height={500}>
<svg ref={node => this.node = node} width={500} height={500}></svg>
<BarChart datum = { expressionDatum.getDatumForNeuron(this.state.neuron_name) }/>
</div>
}
如何让contentGenerator
函数看到this
对象?
答案 0 :(得分:0)
我可以通过分配that = this
然后访问that
来设置状态:
var that = this;
chart.tooltip.contentGenerator(function (d) {
var html = "<div>";
d.series.forEach(function(elem){
Object.keys(data_obj).forEach(function(key_1) {
var outer_obj = data_obj[key_1];
if (outer_obj["key"] === elem.key) {
that.showBarChart(elem.key);
var expr = outer_obj["values"][0]["expr"];
html += "<p>" + elem.key + "</p>";
html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";
}
});
})
html += "</div>";
return html;
});
虽然当nvd3
像疯了一样打印tooltips
时会导致一个奇怪的错误,但我可以更新状态。