React 清除浏览器记住密码框组件
  • 分类:前端开发
  • 发表:2018-12-18
  • 围观(2,376)
  • 评论(0)

最近项目中有一个需求:清除浏览器记住密码。故写了这么个组件。

import React from 'react';
import { Input } from 'antd';

class PasswordInput extends React.Component {

  static getDerivedStateFromProps(nextProps) {
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }

  constructor(props) {
    super(props);

    const value = props.value;
    this.state = {
      showValue: value,
      value,
    };
  }
  componentWillReceiveProps(newProps) {
    if (newProps.value === '') {
      this.setState({ value: '', showValue: '' });
    }
  }
  handleChange = (e) => {
    let newValue;
    const value = e.target.value;
    const currValue = value[value.length - 1]; // 当前值
    const showValue = new Array(value.length + 1).join('*');
    const oldValue = this.state.value;
    if (currValue !== '*') {
      newValue = oldValue.substr(0, showValue.length - 1) + currValue;
    } else {
      newValue = oldValue.substr(0, showValue.length);
    }
    this.setState({ value: newValue, showValue });
    this.triggerChange(newValue);
  }
  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  }
  render() {
    return (<span>
      <Input
        value={this.state.showValue}
        type="text"
        onChange={this.handleChange}
      />
    </span>);
  }
}


export default PasswordInput;

 

微信扫一扫下方二维码,阅读全文~

共有 0 条评论

Top