2017-02-13 94 views
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不起作用。

有关这个问题的任何想法?

在此先感谢。

回答

1

因为你写了两次,其中第二覆盖〜第

<input 
    className={this.state.errorVisible ? this.props.errorClass : this.props.inputClass} 
    //... 
    className={this.props.inputClass} 
/> 

保持1ˢᵗ并删除2ⁿᵈ这是className={this.props.inputClass}

+0

谢谢,稍有不慎:) –

+0

你是欢迎 –

相关问题