简体   繁体   中英

Using Javascript to class manipulation in ReactJs

Is it valid to use Javascript codes within a ReactJs project? I have something like this,

JS

myFunc(e) {
     let v = e.target.value

     if(v.length > 0) {
         e.target.parentNode.setAttribute('class', 'abc')
     }
     else {
         e.target.parentNode.setAttribute('class', 'xyz')
     }
}

HTML

<input ref="xxx" onBlur={this.myFunc.bind(this)} name="xxx" className="xxx" type="text">

This method works as I wanted but not sure weather it's safe to use such codes in ReactJs or not. Please advise me.

It works but generally this is not the promoted way to go. Since I don't know exactly what goes on in the rest of your code, below is my implementation based on your input above:

export default class BlurrableInput extends React.Component {
    constructor() {
        this.state = {
             text = null
        };
    }
    handleInputBlur() {
        console.log('Hello from blur');
    }
    handleInputChange(event) {
        this.setState({
            text: event.target.value
        });
    }
    render() {
        let className = this.state.text !== null && this.state.text.length > 0 ? 'abc' : 'xyz';
        return(
            <input 
                 ref='xxx' 
                 onBlur={this.handleInputBlur} 
                 value={this.state.text} 
                 name='xxx' 
                 className={className} 
                 type='text' />
        );
    }
}

Ps. For the classname generation I can highly recommend this library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM