按钮上的切换图标单击反应

问题描述 投票:0回答:2

我在React应用程序中单击时试图切换按钮图标。我看着控制台,“ togglePassword”的值在单击时发生变化,但按钮图标未发生变化。如何更正此错误?这是我的代码...

class Register extends Component {

    constructor() {
        super();
        this.state = {
            togglePassword: false
        };

        this.onToggle = this.onToggle.bind(this);
    }

    onToggle(e) {
      this.setState({ togglePassword: !this.state.togglePassword })
    }

    render() {
       return (
          <button onClick={this.onToggle} type="button">
             {
              this.state.togglePassword ? 
              <i className="fas fa-eye-slash"></i> : 
              <i className="fas fa-eye"></i>
             }
          </button>
       );
    }
}
javascript reactjs icons toggle react-component
2个回答
1
投票

除了您提供的代码外,还有其他可能,

下面的代码段,这是您的代码的精确副本,并且可以正常工作:


class App extends React.Component {

    constructor() {
        super();
        this.state = {
            togglePassword: false
        };

        this.onToggle = this.onToggle.bind(this);
    }

    onToggle(e) {
      this.setState({ togglePassword: !this.state.togglePassword })
    }

    render() {
       return (
          <button onClick={this.onToggle} type="button">
             {
              this.state.togglePassword ? 
              "fa-eye-slash": 
              "fa-eye"
             }
          </button>
       );
    }
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

0
投票

尝试一下:

 render() {
  const {togglePassword} = this.state
       return (
    <button onClick={this.onToggle} type="button">
           <i className={`fas fa-eye${togglePassword?"-slash:""}`}></i>
     </button>)
}
© www.soinside.com 2019 - 2024. All rights reserved.