ReactJS: Is there a better way of doing this?

Ash*_*Ash 0 javascript reactjs

Basically, on hover i am changing the text color of a link, I was able to achieve what i needed, however, this looks too much of code for me, I believe there should be a better way. I am wondering if there is a better logic than this. Please suggest.

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      link_su: false,
      link_si: false
    };
  }

  componentDidMount() {
    this.hover_signup = document.getElementById("signup");
    this.hover_signin = document.getElementById("signin");

    this.hover_signup.addEventListener("mouseenter", this.colorChange);
    this.hover_signup.addEventListener("mouseleave", this._colorChange);

    this.hover_signin.addEventListener("mouseenter", this.colorChange);
    this.hover_signin.addEventListener("mouseleave", this._colorChange);
  }

  componentWillUnmount() {
    //removing all event listeners.
  }

  colorChange = e => {
    if (e.target.id == "signup") {
      this.setState({ link_su: !this.state.link });
    } else {
      this.setState({ link_si: !this.state.link });
    }
  };

  _colorChange = e => {
    if (e.target.id == "signup") {
      this.setState({ link_su: this.state.link });
    } else {
      this.setState({ link_si: this.state.link });
    }
  };

  render() {
    return (
      <main role="main" className="inner cover">
        <a
          href="/signup"
          className="btn btn-lg btn-secondary"
          style={link_su ? { color: "white" } : { color: "#282c34" }}
          id="signup"
        >
          Sign Up
        </a>
        <br />
        <br />
        <a
          href="/signin"
          className="btn btn-lg btn-secondary"
          style={link_si ? { color: "white" } : { color: "#282c34" }}
          id="signin"
        >
          Sign In
        </a>
      </main>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*ody 5

是的,有一种更简单的方法,这可以使用:hover选择器通过CSS完成。

例如:

a {
  color: blue;
}

a.link1:hover {
  color: red;
}

a.link2:hover {
  color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<a class="link1" href="">Link 1</a>
<a class="link2" href="">Link 2</a>
Run Code Online (Sandbox Code Playgroud)

编辑

如果您使用style属性来应用样式,那么我相信没有任何东西(!important属性除外)可以覆盖该样式,因此,如果您通过样式提供了初始颜色,但是在样式表中提供了悬停颜色,则悬停颜色将被初始样式覆盖并没有出现。因此,最好不要混合使用内联样式和样式表样式。

这是发生的情况的示例:

a.link1:hover {
  color: red;
}

a.link2:hover {
  color: red !important;
}
Run Code Online (Sandbox Code Playgroud)
<a class="link1" style="color: blue;" href="">Always Blue</a>
<a class="link2" style="color: blue;" href="">Using Important (but you shouldn't)</a>
Run Code Online (Sandbox Code Playgroud)

注意:我实际上不建议在!important这里使用该标志,而是建议删除内联样式。

  • React中的CSS集成并不是那么简单!应该使用`className`代替`class`,可以使用CSS-in-JS或普通CSS,存在范围CSS等问题! (2认同)