javascript - TypeError:无法读取 null 的属性“不透明度”
问题描述
将鼠标悬停在 React recharts 中的图例上时,我正在尝试实现不透明度更改:https ://jsfiddle.net/alidingling/1p40zzfe/
但是,我总是收到错误消息:TypeError:无法读取 null 的属性“不透明度”。有什么原因吗?它的 Legend 组件具有导致问题的“OnMouseEnter”和“OnMouseLeave”行。
谢谢
class EducationPageRouter extends React.Component{
getInitialState() {
return {
opacity: {
car: 1,
phone: 1,
},
};
}
handleMouseEnter(o) {
const { dataKey } = o;
const { opacity } = this.state;
this.setState({
opacity: { ...opacity, [dataKey]: 0.5 },
});
}
handleMouseLeave(o) {
const { dataKey } = o;
const { opacity } = this.state;
this.setState({
opacity: { ...opacity, [dataKey]: 1 },
});
}
render() {
const { opacity } = this.state;
return (
<Card>
<CardContent>
<Typography variant="title" color="primary" gutterBottom="true">
Sales Information Display
</Typography>
<Typography variant="header1" color="primary" gutterBottom="true">
Line Graph - Number of Sales to Date Time
</Typography>
<Button variant="raised" color="primary">
Switch
</Button>
<ResponsiveContainer width="95%" aspect={9.5/3.8}>
<LineChart
data={formattedSales}
margin={{ top:5, right:10, bottom:5, left:20 }}
>
<XAxis
dataKey="date"
padding={{ left:0, right:50 }}
style={{ fontFamily: "Roboto, sans-serif" }}
tick={{ fontSize: "12.5px"}}
/>
<YAxis
dataKey="car"
/>
<CartesianGrid
stroke="#f5f5f5"
strokeDasharray="2.5 2.5"
/>
<Tooltip
wrapperStyle={{ fontFamily: "Roboto, sans-serif" }}
/>
<Legend
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
wrapperStyle={{ fontFamily: "Roboto, sans-serif" }}
verticalAlign="bottom"
height={40}
/>
<Line
type="monotone"
dataKey="car"
stroke="#4169e1"
/>
<Line
type="monotone"
dataKey="phone"
stroke="#fa8072"
/>
</LineChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
}
解决方案
getInitialState
只能用 with createReactClass
,所以你的状态会是null
。您可以改为在构造函数中设置初始状态,或使用类属性。
您的事件处理程序handleMouseEnter
并handleMouseLeave
没有被绑定,因此this
不会是您所期望的。解决这个问题的一种方法是将它们绑定到this
构造函数中,或者将它们变成属性初始化的箭头函数。
class EducationPageRouter extends React.Component {
state = {
opacity: {
car: 1,
phone: 1,
}
};
handleMouseEnter = o => {
const { dataKey } = o;
const { opacity } = this.state;
this.setState({
opacity: { ...opacity, [dataKey]: 0.5 }
});
};
handleMouseLeave = o => {
const { dataKey } = o;
const { opacity } = this.state;
this.setState({
opacity: { ...opacity, [dataKey]: 1 }
});
};
// ...
}
推荐阅读
- python - BeautifulSoup - 在标签后获取文本
- scheme - 等待几秒钟后调用Scheme中的过程?
- vue.js - 使用 Auth Flow With PKCE、MSAL v2、Vue.js 和 Azure Functions 获取 Azure B2C 用户权限(授权用户)
- button - 使用存储在 Google 表格中的 URL 的 Google 站点导航按钮
- r - R - 如何在组内找到变量的对组合
- node.js - Mongoose,MATCH 运算符不返回结果
- arrays - 为什么由 document.getElementById('table') 定义的变量 tbl 返回 null?
- php - 如何防止后退按钮进入 laravel 中的默认身份验证主页?
- apache-spark - delta Lake - 在 pyspark 中插入 sql 失败并出现 java.lang.NoSuchMethodError: org.apache.spark.sql.catalyst.expressions.Alias
- c# - 检索信息 BsonDocument