为多个字段反应密码眼睛图标

use*_*401 5 reactjs

我有三个密码字段,每个字段都有一个眼睛图标让消费者显示/隐藏密码,

我正在尝试使用以下代码,但是如果我单击一个字段的隐藏/显示,那么它也会影响其他字段。

请指导我纠正以下代码的任何示例

class ShowPassword extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      type: 'input',
      score: 'null'
    }
    this.showHide = this.showHide.bind(this);
  }

  showHide(e){
    //e.preventDefault();
    //e.stopPropagation();
    this.setState({
      type: this.state.type === 'input' ? 'password' : 'input'
    })  
  }


  render(){
    return(
      <div>
      <label className="password">Current Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>

            <label className="password">New Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>

            <label className="password">Confirm Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>
        </div>
    )
  }
}

ReactDOM.render(<ShowPassword/>, document.getElementById('react'));
Run Code Online (Sandbox Code Playgroud)

下面是要玩的 jsbin 链接

https://jsbin.com/homuxoq/edit?html,css,js,output

dsc*_*chu 4

将您的输入字段提取到它自己的组件中

class PasswordField extends React.Component{
  state = {
    type: 'text',
  }


  handleClick = () => this.setState(({type}) => ({
    type: type === 'text' ? 'password' : 'text'
  }))


  render() {
    const { label } = this.props

    return (
      <label className="password">{label}
        <input type={this.state.type} className="password__input"/>
        <span className="password__show" onClick={this.handleClick}>{this.state.type === 'text' ? 'Hide' : 'Show'}</span>
      </label>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

链接到 JSBin

我想在这里提到的另一件事是,没有input. 因此我将其替换为有效值text