问题
I want to call a function from d3 event handler. I'm able to access on click event as I'm able to print console message but if I call function from there it is giving error.
I'm getting following error:
bundle.js:96593 Uncaught TypeError: Cannot read property 'selectNodeById' of undefined at SVGGElement. (bundle.js:96593) at SVGGElement.__onclick (bundle.js:28032)
Code:
import React, { Component } from 'react';
import NVD3Chart from 'react-nvd3';
import d3 from 'd3';
const datum = [{
x: 'Meter 1',
y: 5
}, {
x: 'Meter 2',
y: 2
}, {
x: 'Meter 3',
y: 9
}, {
x: 'Meter 4',
y: 7
}, {
x: 'Meter 5',
y: 4
}, {
x: 'Meter 6',
y: 3,
}, {
x: 'Meter 7',
y: 0.5
}];
const tooltip = d3.select('body')
.append('div')
.style('position', 'absolute')
.style('padding', '9px')
.style('font', '12px')
.style('font-family', 'sans-serif')
.style('background', 'steelblue')
.style('color', 'white')
.style('text-align', 'center')
.style('z-index', '10')
.style('cursor', 'pointer')
.style('visibility', 'hidden')
.style('border', '1px')
.style('border-radius', '3px')
.style('pointer-events', 'none')
.text('ahu tooltip');
export default class extends Component {
constructor(props) {
super(props);
this.selectNodeById = this.selectNodeById.bind(this);
}
selectNodeById() {
console.log('in select node func');
}
renderEnd() {
d3.selectAll('.nv-pie').selectAll('.nv-slice').style('cursor',
'pointer')
.on('mouseover', (event) => {
tooltip.style('left', (d3.event.clientX + 30) + 'px')
.style('top', (d3.event.clientY - 40) + 'px');
tooltip.html(() => '<strong>' + event.data.x + '</strong> <br/>
<span style= {
"color:red"
} > ' + event.data.y + ' < /span>');
tooltip.style('visibility', 'visible');
})
.on('mouseout', () => {
tooltip.style('visibility', 'hidden');
})
.on('click', () => {
this.selectNodeById();
tooltip.style('visibility', 'hidden');
});
}
render() {
return ( < NVD3Chart x = {
d => d.x
}
y = {
d => d.y
}
id = {
'pieChart'
}
type = {
'pieChart'
}
datum = {
datum
}
useInteractiveGuideline = {
true
}
transitionDuration = {
500
}
showLegend = {
false
}
growOnHover = {
true
}
ready = {
this.renderEnd
}
/>
);
}
}
来源:https://stackoverflow.com/questions/48822609/unable-to-call-function-from-from-d3-event-handler