react入门-组件方法、数据和生命周期

react组件也像vue一样,有data和methods,但是写法就很不同了:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>state</title>
</head>
<body>
    <div id="app"></div>
    <script src="common/react.js"></script>
    <script src="common/react-dom.js"></script>
    <script src="https://cdn.bootcss.com/babel-core/5.8.38/browser.js"></script>
    <script type="text/babel">
        class App extends React.Component {
            constructor(props) {
                super(props)
                //data react官方这边叫state,在组件contructor上面定义
                this.state = {
                    count: 0
                }
            }
            //最常用个的生命钩子WillMount,DidMount,WillUpdate,DidUpdat
            componentWillMount() {
                console.log('1.componentWillMount')
            }
            componentDidMount() {
                console.log('2.componentDidMount')
            }
            componentWillUpdate(){
                console.log('4.componentWillUpdate')
            }
            componentDidUpdate(){
                console.log('3.componentDidUpdate')
            }
            add(event) {
                console.log('add')
                // 如果只写这"state.count++"react是不会自动重新去render组件的
                // this.state.count++
                // 只有调用setState react才会重新渲染组件
                this.setState({count: this.state.count+1})
            }
            //组件必须的render函数,相当于vue的<template>...</template> 调用自定义函数时必须bind(this)
            render() {
                return (<div>
                    <input type="text" value={this.state.count}/>
                    <input type="button" value="add" onClick={this.add.bind(this)}/>                    
                </div>)
            }
        }
        //渲染到#app上
        ReactDOM.render(
           <App/>,
           document.querySelector('#app')
        )
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/amiezhang/p/8505272.html