1. 程式人生 > >React-菜鳥學習筆記(二)

React-菜鳥學習筆記(二)

 

這篇新穎的東西是React的元件的封裝和引用

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"
></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> /*jsx允許在模板中插入陣列,陣列會自動展開所有成員*/ /** var arr = [ <h1>白</h1>, <h1>富</h1>, <h1>美</h1>, <h1>甜</h1> ]; var element = ( <div> <h1>Hello, world! </h1> {arr} </div> ) ReactDOM.render( element, document.getElementById('example') );
*/ /* React元件 封裝一個輸出為‘hello world’的React元件,元件名為HelloMessage*/ /*Tips: 原生HTML元素名以小寫字母開頭,而自定義的React類名以大寫字母開頭。組建類只能包含一個頂層標籤 return <div><h1>hello world</h1><div/> 是錯的*/ /*方法1 使用函式定義一個元件 方法2 使用ES6 class定義一個元件*/ /** function HelloMessage(props){ return <h1>hello world: {props.name}</h1> } class Welcome extends React.Component{ render(){ return <h1>welcome slowcity</h1>; } } const element = <div> <HelloMessage name='superMan'/> <Welcome /> </div> ReactDOM.render( element, document.getElementById('example') );
*/ /*複合元件 直白點就是封裝元件*/ /** function Name(props) { return <h1>網站名稱:{props.name}</h1>; } function Url(props) { return <h1>網站地址:{props.url}</h1>; } function Nickname(props) { return <h1>網站小名:{props.nickname}</h1>; } function App() { return ( <div> <Name name="造夢工場" /> <Url url="https://www.cnblogs.com/" /> <Nickname nickname="Slowcity" /> </div> ); } const element =( <App />) ReactDOM.render( element, document.getElementById('example') ); */ /*將生命週期方法新增到類中 掛載和解除安裝*/ /* Tips: ()=>this.tick() 是 ES6 中宣告函式的一種方式,叫做箭頭函式表示式,引入箭頭函式有兩個方面的作用:更簡短的函式並且不繫結 this。 var f = ([引數]) => 表示式(單一) // 等價於以下寫法 var f = function([引數]){ return 表示式; } 箭頭函式的基本語法: (引數1, 引數2, …, 引數N) => { 函式宣告 } (引數1, 引數2, …, 引數N) => 表示式(單一) //相當於:(引數1, 引數2, …, 引數N) =>{ return 表示式; } // 當只有一個引數時,圓括號是可選的: (單一引數) => {函式宣告} 單一引數 => {函式宣告} // 沒有引數的函式應該寫成一對圓括號。 () => {函式宣告} */ class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } //新增定時器 生命週期鉤子 當 Clock 的輸出插入到 DOM 中時,React 呼叫 componentDidMount() 生命週期鉤子 componentDidMount(){ this.timerID = setInterval( () => this.tick(),1000 ); } //移除定時器 一旦 Clock 元件被從 DOM 中移除,React 會呼叫 componentWillUnmount() 這個鉤子函式 componentWillUnmount(){ clearInterval(this.timerID); } tick(){ this.setState({ date:new Date() }); } render() { return ( <div> <h1>Hello, world!</h1> <FormattedDate date={this.state.date}/> <h2>hello{this.props.name} 現在是 {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } Clock.defaultProps={ name:"慢城" } function FormattedDate(props) { return <h2>現在是 {props.date.toLocaleTimeString()}.</h2>; } ReactDOM.render( <Clock />, document.getElementById('example') ); </script> </body> </html>