当状态改变时,反应className不会更新

时间:2017-02-13 17:59:28

标签: reactjs jsx

我有一个更新className的TextInput组件。

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>
        );
    }
}

log console.log(this.state.errorVisible?this.props.errorClass:this.props.inputClass)正常工作,但className不起作用。

对这个问题有任何想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

因为你写了两次,第二次覆盖是第一次

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

保持1ˢᵗ并删除className={this.props.inputClass}

的2ⁿᵈ