首页 > 代码库 > React State

React State

1.getInitialState:设置初始State,返回Object

2.this.setState():改变State

3.都在creatClass内创建类

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,
    minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <script src="http://www.mamicode.com/lib/react.js"></script>
    <script src="http://www.mamicode.com/lib/react-dom.js"></script>
    <script src="http://www.mamicode.com/lib/browser.min.js"></script>
    <title></title>
</head>
<body>
<div id="example"></div>

</body>
<script type="text/babel">
    var LikeButton = React.createClass({
        getInitialState: function() {
            return {liked: false};
        },
        handleClick: function(event) {
            this.setState({liked: !this.state.liked});
        },
        render: function() {
            var text = this.state.liked ? ‘喜欢‘ : ‘不喜欢‘;
            return (
                    <p onClick={this.handleClick}>
                    你<b>{text}</b>我。点我切换状态。
                </p>
            );
        }
    });

    ReactDOM.render(
            <LikeButton />,
            document.getElementById(‘example‘)
    );
</script>
</html>

  

React State