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
}
編集 render メソッドを編集し、イベントを処理する関数を追加しましたが、次のようになりました。
警告: setState(...): 既存の状態遷移中 ( 内などrender
) に更新できません。Render メソッドは props と 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' })
}
.....