react 组件state属性

时间:2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="test">

</div>

<script src="js/react.development.js"></script>
<script src="js/react-dom.development.js"></script>
<script src="js/babel.min.js"></script>
<script src="js/prop-types.js"></script>

<script type="text/babel">
    // 创建组件
    class MyConponent extends React.Component{
        constructor(props) {
            super(props);
            this.state = {
                flag:false
            };
            // 修改自定义方法this指向
            this.handleClick = this.handleClick.bind(this);
        }

        // 处理点击事件
        handleClick(){
            let flag = !this.state.flag;
            this.setState({flag});
        }

        render(){
            return <h1 onClick={this.handleClick}>{this.state.flag?'我喜欢你':'你喜欢我'}</h1>;
        }
    }

    // 渲染虚拟dom
    ReactDOM.render(<MyConponent/>,document.getElementById('test'));
</script>
</body>
</html>