通过事件响应更改输入类型 [英] React changing input type via event
问题描述
我正在尝试扩展一个React输入组件,它需要是类型密码,并且在它旁边的元素或元素上的某个事件之后 - 它需要切换输入的类型(type =text / password )。
I'm trying to extend a React input component, which needs to be type password and after certain event on the element or element next to it - it needs to toggle the type of the input (type="text/password").
React如何处理这个问题?
How this can be handled by React?
我将此作为我的组件的类:
I have this as class for my component:
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
}
编辑
我编辑了渲染方法并添加了一个功能处理事件,但我现在得到:
EDIT I've edited the render method and added a function that handles the event, but I'm now getting:
警告:setState(...):在现有状态转换期间无法更新(例如呈现
)。渲染方法应该是道具和状态的纯函数。
Warning: setState(...): Cannot update during an existing state transition (such as within render
). Render methods should be a pure function of props and state.
我的浏览器崩溃了。
.....
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' })
}
.....
推荐答案
您可以配置根据组件的状态输入输入的类型,并在某个事件上设置它,例如:
You can configure the type of the input according to component's state, and set it on some event, for example:
< 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
功能。
这篇关于通过事件响应更改输入类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!