How to set conditional classes in react?

时间:2016-07-11 21:05:50

标签: javascript reactjs

I am trying to understand conditional variables using Reactjs. Using plain ol' HTML and jQuery, for instance, my code would look like so.

HTML:

<p class="aclass">Error</p>
<input id="dabox" type="text" />
<input id="dabutton" type="button" value="Ship It" />

JQuery:

$('#dabutton').click(function(){
if ( $('#dabox').val()== "" ){
$('.aclass').addClass('error');
}
});  

CSS:

.error {color: red;}
.aclass {//does nothing//}

I am having trouble understanding how to conditionally set the class using Reactjs. My best guess is something like so:

JavaScript

runcheck:function(){
if ( document.getElementById('dabox').value == 0 ){
var depends = "aclass error";
}
},

render:function(){
var depends = "aclass";
return (
<p className={depends}>Error</p>
<input onClick="runcheck()" type="submit"/>
)
}

Naturally the code doesn't work. How would I go about setting these variables conditionally using Reactjs?

1 个答案:

答案 0 :(得分:2)

Your example illustrates some of the fundamental mindset changes you need when working with React. They're not difficult to grasp, for starters take a look at:

And here's some code for you:

import React from 'react';

export default React.createClass({
    /**
     * Component's current (internal) state
     */
    getInitialState() {
        return {
            text: '' // initial value for text input
        };
    },

    /**
     * Renders virtual DOM according to component's current state
     */
    render() {
        const showError = this.state.text == '';

        return <div>
            { showError
                    ? <p className='error'>Error</p>
                    : null
            }

            <input type='text' value={this.state.text} onChange={this.onChange} />
            <input type='button' onClick={this.onClick} value='Ship It' />
        </div>
    },

    /**
     * Every time the textbox is changed, this handler is called.
     * It simply updates the component's state
     */
    onChange(ev) {
        // State changes cause render to be re-evaluated and your DOM will be updated accordingly.
        this.setState({ text: ev.target.value });
    },

    /**
     * When the button is clicked, this handler is called
     */
    onClick() {
        // ...
    }
});