reactjs - 有条件地在点击事件上设置 SVG 样式,但对实际点击不起作用
问题描述
我正在尝试通过添加样式类有条件地更改点击事件上两个 svg 图标的填充。
我已经设法获得了在点击设置时添加类的条件,并设置了 svgs 的样式。但是,我无法在点击时更改样式。我正在使用 react-inlinesvg 包将我的 svg 图标作为内联元素。
class NavBar extends Component {
constructor(props) {
super(props);
this.state = {
show: false
};
}
//changes state for conditional to work
showDropdown() {
const { show } = this.state;
this.setState({
show: !show
});
}
render() {
const styles = require('./styles.scss');
const { show } = this.state;
const hamburger = require('./hamburger.svg');
//checks if icon was clicked
const iconClicked = show ? styles.iconClicked : null
return (
<div>
//click event
<button type="button" className={styles.hamburger} onClick={() => this.showDropdown()}>
{/*conditionally adds class to change icon color*/}
<SVG className={iconClicked} src={hamburger} alt="hamburger" />
</button>
</div>
);
}
}
export default withRouter(NavBar);
在 ./styles.scss :
.iconClicked path{
fill: blue !important;
}
./hamburger.svg
<svg xmlns="http://www.w3.org/2000/svg" width="339" height="290" viewBox="0 0 339 290">
<title>hamburger</title>
<style>
path {
fill:purple;
}
</style>
<path d="M267,406H424a10,10,0,0,1,10,10v0.137a10,10,0,0,1-10,10H267a10,10,0,0,1-10-10V416A10,10,0,0,1,267,406Zm0,73.591H424a10,10,0,0,1,10,10v0.137a10,10,0,0,1-10,10H267a10,10,0,0,1-10-10v-0.137A10,10,0,0,1,267,479.591Zm0,71.272H424a10,10,0,0,1,10,10V561a10,10,0,0,1-10,10H267a10,10,0,0,1-10-10v-0.137A10,10,0,0,1,267,550.863Z" transform="translate(-176 -343)"/>
</svg>
当我单击返回页面并返回时,图标会改变颜色,但在实际点击时不会。
解决方案
我认为问题在于您忘记为该方法进行绑定。触发点击事件时,您的状态不会改变。
class NavBar extends Component {
constructor(props) {
super(props);
this.state = {
show: false
};
// Added binding here
this.showDropdown = this.showDropdown.bind(this);
}
}
推荐阅读
- swift - SwiftUI 中的几何阅读器是什么?
- android - 使用 RN 和 expo 更改 android 上的导航栏?
- android - 使用颤振通过http连接发送文件的问题
- pymongo - PyMongo 检索数据库值
- python - 在总和为 0 的列表中生成随机唯一数字
- ruby-on-rails - 是否可以在同一个 Rails 应用程序上拥有多个具有不同域名的网站?
- python - protobuf 数据解析返回错误结果
- tensorflow - 当我在 Anaconda Prompt 中更新 tensorflow 和 keras 时,这条消息意味着什么?是错还是好的?
- sql - 使用活动记录来实现这个sql是更好的方法吗?
- django - 如何在Angular中设置惰性模块文件加载路径,js文件在Apache中找不到