0
我有一個更新className的TextInput組件。當狀態發生變化時,反應className不更新
class TextInput extends React.Component{
constructor(props){
super(props);
this.state = {
errorVisible: false,
textErrorClass: '',
errorMessage: ''
}
this.onChange = this.onChange.bind(this);
}
onChange(ev){
let isValid = true,
errorMessage = '';
const value = ev.target.value;
if(this.props.required && value.length === 0){
isValid = false;
errorMessage = 'Campo obrigatório';
}
else if(this.props.minLength > 1 && value.length < this.props.minLength && value.length > 0){
isValid = false;
errorMessage = `Campo deve possuir pelo menos ${this.props.minLength} caracteres`;
}
this.props.onChange(ev, isValid);
this.setState({
errorVisible: !isValid,
textErrorClass: isValid ? '' : this.props.textErrorClass,
errorMessage,
})
}
render(){
console.log(this.state.errorVisible ? this.props.errorClass : this.props.inputClass);
return(
<div>
<input className={this.state.errorVisible ? this.props.errorClass : this.props.inputClass}
type={this.props.type}
name={this.props.name}
placeholder={this.props.text}
maxLength={this.props.maxLength}
className={this.props.inputClass}
onChange={this.onChange}
defaultValue={this.props.defaultValue}
/>
{this.state.errorVisible && <div className={this.state.textErrorClass}>{this.state.errorMessage}</div> }
</div>
);
}
}
日誌的console.log(this.state.errorVisible this.props.errorClass:this.props.inputClass)正常工作,但一個className不起作用。
有關這個問題的任何想法?
在此先感謝。
謝謝,稍有不慎:) –
你是歡迎 –