首页 > 解决方案 > 有条件地在点击事件上设置 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>

当我单击返回页面并返回时,图标会改变颜色,但在实际点击时不会。

标签: reactjs

解决方案


我认为问题在于您忘记为该方法进行绑定。触发点击事件时,您的状态不会改变。

    class NavBar extends Component {
      constructor(props) {
        super(props);
        this.state = {
          show: false
        };
        // Added binding here
        this.showDropdown = this.showDropdown.bind(this);
      }
    }

推荐阅读