Реагировать на изменение типа ввода через событие

Я пытаюсь расширить компонент ввода React, который должен иметь тип пароля и после определенного события в элементе или элементе рядом с ним - ему необходимо переключить тип ввода (type = "text / password").

Как с этим справится React?

У меня это как класс для моего компонента:

import { React, Component } from 'lib' 

export class PasswordInput extends Component {
constructor(props, context){
    super(props, context)
    const { type, validate, password } = this.props

    if(context.onValidate && password) {
        context.onValidate(password, validate)
    }

    if(context.showHide && password) {
        context.onValidate(password, validate)
    }
}

render() {
    let inputType = 'password'

    return (
        <div className="form">
            <label htmlFor="password">{ this.props.label }</label>
            <input {...this.constructor.filterProps(this.props)} type={ inputType } />
            { this.props.touched && this.props.error && <div className="error">{ this.props.error }</div> }
            <button onClick={ showHide() }>{ this.props.btnLabel }</button>
        </div>
    )
}

showHide(field) {
    return function(event){
        console.log(`state before is ${this.state}`)
    }
}

// the meld is
// export function meld(...objects) {
//     return Object.assign({}, ...objects)
// }

  static filterProps(props) {
      const result = meld(props)
      delete(result.validate)
      return result
  }
}

PasswordInput.contextTypes = {
    onValidate: React.PropTypes.func
}

ИЗМЕНИТЬ. Я отредактировал метод рендеринга и добавил функцию, которая обрабатывает событие, но теперь получаю:

Предупреждение: setState (...): невозможно обновить во время существующего перехода состояния (например, в пределах render). Методы визуализации должны полностью зависеть от свойств и состояния.

И мой браузер вылетает.

.....

    render() {
    return (
        <div className="form__group">
            <label htmlFor="password">{ this.props.label }</label>
            <input {...this.constructor.filterProps(this.props)} type={ this.state.inputType } />
            { this.props.touched && this.props.error && <div     className="form__message form__message_error">{ this.props.error }</div> }
            <button onClick={ this.handleClick() }>{ this.props.btnLabel }</button>
        </div>
    )
}

handleClick(){
    this.setState({ inputType: this.state.inputType === 'password' ? 'text' : 'password' })
}

.....


person Vladyn    schedule 07.06.2016    source источник


Ответы (1)


Вы можете настроить тип входа в соответствии с состоянием компонента и установить его на какое-то событие, например:

<input {...this.constructor.filterProps(this.props)} type={ this.state.inputType } onChange={ event => this.onChange(event) } />

И реализуем метод onChange:

onChange(event) {
    var length = event.currentTarget.value.length;
    this.setState({ inputType: length < 5 ? 'text' : 'password' });
}

Возможно, вам придется привязать функцию onChange.

person Gilad Artzi    schedule 07.06.2016
comment
Спасибо за это. К сожалению, это дает мне TypeError: this.state is null - person Vladyn; 07.06.2016
comment
Я забыл объявить состояние - this.state = {inputType: 'password'} - мой плохой - person Vladyn; 07.06.2016
comment
У меня было то же самое, но я получаю ошибку A component is changing an uncontrolled input of type password to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. - person CrsCaballero; 27.02.2020