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 } //如果不bind(this)下面dom元素调用的时候this将会是undefined //这个是react的大坑 this.add = this.add.bind(this) } //最常用个的生命钩子WillMount,DidMount,WillUpdate,DidUpdat componentWillMount() { console.log(‘1.componentWillMount‘) } componentDidMount() { console.log(‘2.componentDidMount‘) } componentWillUpdate(){ console.log(‘4.componentWillUpdate‘) } componentDidUpdate(){ console.log(‘3.componentDidUpdate‘) } //自定义方法,注意需要在constructor上bind(this) 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> render() { return (<div> <input type="text" value={this.state.count}/> <input type="button" value="add" onClick={this.add}/> </div>) } } //渲染到#app上 ReactDOM.render( <App/>, document.querySelector(‘#app‘) ) </script> </body> </html>