React.js - 无法读取未定义的 属性,即使上下文已绑定(从子调用父方法)
React.js - Cannot read property of undefined, even though context is bound (call parent method from child)
我正在用 React 构建一个小应用程序——当在子组件中单击条形图 (ApexCharts) 中的条时,尝试从我的父组件 Job
调用一个函数 SummaryChart
.
自然地,我读到的方法是在 Job 中定义一个名为 getSequenceView
的函数,然后将其通过别名 handleBarClick
的 prop 传递给 Chart,然后调用 this.props.handleBarClick
来自 SummaryChart
以在父级中调用它。
父组件
class Job extends Component {
constructor(props)
{
super(props);
this.state = {
...
}
this.getSequenceView = this.getSequenceView.bind(this);
}
getSequenceView(config, event)
{
console.log(config.someData);
$('#help-modal').modal();
}
render()
{
return (
<SummaryChart
handleBarClick={this.getSequenceView}
/>
);
}
子组件
class SummaryChart extends Component {
constructor(props) {
super(props);
this.state = {
options: {
chart: {
events: {
dataPointSelection: function(event, chartContext, config) {
this.props.handleBarClick();
},
}
}
}
render() {
return (
<Chart
options={this.state.options}
series={this.state.series}
type="bar"
width="100%"
/>
);
}
}
ApexCharts docs for handling events here!
我有一种感觉,因为我将 this.state.options
作为道具传递给来自 ApexCharts 的实际 Chart
对象,所以当点击栏时,事件从 Chart
注册object 而不是 SummaryChart
,也许这就是我收到错误的原因。
app.js:66798 Uncaught TypeError: Cannot read property 'handleBarClick'
of undefined
问题
在构造函数中 this.props
尚未设置。
解决方案
访问传递给构造函数的道具。
constructor(props) {
super(props);
this.state = {
options: {
chart: {
events: {
dataPointSelection: function (event, chartContext, config) {
props.handleBarClick();
}
}
}
}
};
}
我正在用 React 构建一个小应用程序——当在子组件中单击条形图 (ApexCharts) 中的条时,尝试从我的父组件 Job
调用一个函数 SummaryChart
.
自然地,我读到的方法是在 Job 中定义一个名为 getSequenceView
的函数,然后将其通过别名 handleBarClick
的 prop 传递给 Chart,然后调用 this.props.handleBarClick
来自 SummaryChart
以在父级中调用它。
父组件
class Job extends Component {
constructor(props)
{
super(props);
this.state = {
...
}
this.getSequenceView = this.getSequenceView.bind(this);
}
getSequenceView(config, event)
{
console.log(config.someData);
$('#help-modal').modal();
}
render()
{
return (
<SummaryChart
handleBarClick={this.getSequenceView}
/>
);
}
子组件
class SummaryChart extends Component {
constructor(props) {
super(props);
this.state = {
options: {
chart: {
events: {
dataPointSelection: function(event, chartContext, config) {
this.props.handleBarClick();
},
}
}
}
render() {
return (
<Chart
options={this.state.options}
series={this.state.series}
type="bar"
width="100%"
/>
);
}
}
ApexCharts docs for handling events here!
我有一种感觉,因为我将 this.state.options
作为道具传递给来自 ApexCharts 的实际 Chart
对象,所以当点击栏时,事件从 Chart
注册object 而不是 SummaryChart
,也许这就是我收到错误的原因。
app.js:66798 Uncaught TypeError: Cannot read property 'handleBarClick' of undefined
问题
在构造函数中 this.props
尚未设置。
解决方案
访问传递给构造函数的道具。
constructor(props) {
super(props);
this.state = {
options: {
chart: {
events: {
dataPointSelection: function (event, chartContext, config) {
props.handleBarClick();
}
}
}
}
};
}