[深入React] 5.MVC

react 是一种典型的MVC框架。

在jquery中,我们都是针对dom编程,由dom事件触发dom改变,MVC三层代码混在一起。

比如点击变颜色

$('#btn').click(function(){
    $(this).css('background-color','red');
});

在react中

dom事件修改modal(C->M)

function click(){
    // react里使用state作为modal
    this.setState({
        'background-color':'red'
    });
}

modal再根据写好的规则映射到view(M->V)

function render(){
    return <div style={{
        // 这是jsx里style要写成object
        'background-color':this.state['background-color']
    }} />
}

分层是为了代码分离,而实现代码逻辑更清晰

完整代码:

React.createClass({
    render:function(){
        return <div
            onClick={this.click}
            style={{
            // 这是jsx里style要写成object
            'background-color':this.state['background-color']
        }} />
    },
    click:function(){
        this.setState({
            'background-color':'red'
        });
    }
});
posted @ 2016-11-09 17:11  p2world  阅读(343)  评论(0编辑  收藏  举报