我在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>
);
}
}
除了您提供的代码外,还有其他可能,
下面的代码段,这是您的代码的精确副本,并且可以正常工作:
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>
尝试一下:
render() {
const {togglePassword} = this.state
return (
<button onClick={this.onToggle} type="button">
<i className={`fas fa-eye${togglePassword?"-slash:""}`}></i>
</button>)
}