状态没有从真实值reactjs更改为false

时间:2018-09-12 08:10:43

标签: javascript reactjs

我是reactjs的新手。目前,我正在尝试基于onBlur和onFocus事件将input_active的状态设置为true或false。基于input_active值,我更改了输入元素的样式。

下面是代码段,

constructor(props) {
    super(props);
    this.input_text_ref = React.createRef();
    this.state = {
        input_active: 'true',
    };
}
focus = () => {
    console.log("focus");
    this.setState({input_active: 'true'});
    console.log("input_active_focus", this.state.input_active);
};

blur = () => {
    console.log("blur");
    this.setState({input_active: 'false'});
    console.log("input_active_blur", this.state.input_active);
};

render() {
    let input_element_classes = [''];

    if(!this.state.input_active)//out of focus {
        input_element_classes.push('blur');
    }
    if (this.state.input_active) //focused input element {
        input_element_classes.pop();
        input_element_classes.push('focus');
    }


    return (
        <div className={'text_input_wrapper'}>
            <input {...rest}
                className={input_element_classes.join(' ')}
                type="text"
                ref={this.input_text_ref}
                onChange={this.handle_text_input_change}
                onBlur={this.blur}
                onFocus={this.focus}
            />
        </div>
    );
}

下面是CSS,

.focus {
    background-color:green;
}
.blur {
    background-color: red;
}

即使专注于模糊问题,this.state.input_active的值始终为真...如何基于聚焦和模糊更改其值。谢谢。

2 个答案:

答案 0 :(得分:0)

您需要使用truefalse,而不是'true''false'

您正在将字符串分配给state.input_active。如果字符串不为空,则始终求值为true。即使字符串是'false'

答案 1 :(得分:0)

final Image img = pic.get(0);
final float prevX = img.getX(), prevY = img.getY();

img.addListener(new ClickListener(){
    @Override
    public void clicked(InputEvent event, float x, float y) {
        System.out.println("CLICKED!!!");
        if(img.getX() != prevX || img.getY() != prevY)
            img.addAction(Actions.moveTo(prevX, prevY));
        else
            img.addAction(Actions.moveTo(300,700));
    }
});