react入門-組件方法、數據和生命周期
阿新 • • 發佈:2018-03-04
sele viewport otc 定義 emp scrip rip data tex
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>
react入門-組件方法、數據和生命周期