react框架

環境準備

創建項目

npx create-react-app my-react

進入項目並啓動

cd my-react && npm start

src/index.js

先把src裏面的東西全部刪掉,重寫了index.js

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
	render(){
		return (
			<div>Hellow, World</div>
		)
	}
}

ReactDOM.render(<App/>, document.getElementById('root'));

JSX

一個React組件中,render方法中return出去的內容就是這個組件將要渲染的內容,然後Babel 會把 JSX 轉譯成一個名爲 React.createElement() 函數調用。

React.createElement(
  'div',
  {},
  'Hello, World'
)

React.createElement() 接收三個參數:
第一個參數是必填,傳入的是似HTML標籤名稱: ul, li, div;
第二個參數是選填,表示的是屬性: className;
第三個參數是選填, 子節點: 要顯示的文本內容;
React.createElement() 會預先執行一些檢查,以幫助你編寫無錯代碼,但實際上它創建了一個這樣的對象:

// 注意:這是簡化過的結構
const element = {
  type: 'div',
  props: {
    className: '',
    children: 'Hello, world!'
  }
};

元素渲染

與瀏覽器的 DOM 元素不同,React 元素是創建開銷極小的普通對象。React DOM 會負責更新 DOM 來與 React 元素保持一致。
想要將一個 React 元素渲染到根 DOM 節點中,只需把它們一起傳入 ReactDOM.render():

const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));

render方法接收兩個參數,第一個參數爲我們的 React 根級組件,第二個參數接收一個 DOM 節點,代表我們將把和 React 應用掛載到這個 DOM 節點下,進而渲染到瀏覽器中。

組件 & props

組件,從概念上類似於 JavaScript 函數。它接受任意的入參(即 “props”),並返回用於描述頁面展示內容的 React 元素。
函數組件:

function Welcome(props){
	renter (
		<h1> Hello, {props.name} </h1>
	)
}
<Welcome name="World"/>

該函數是一個有效的 React 組件,因爲它接收唯一帶有數據的 “props”(代表屬性)對象與並返回一個 React 元素。這類組件被稱爲“函數組件”,因爲它本質上就是 JavaScript 函數。
class組件:

class Welcome extends React.Component {
	render(){
		renter (
			<h1> Hello, {thhis.props.name} </h1>
		)
	}
}
<Welcome name="World"/>

組件名稱必須以大寫字母開頭。
組件無論是使用函數聲明還是通過 class 聲明,都決不能修改自身的 props。

State & 生命週期

State 與 props 類似,但是 state 是私有的,並且完全受控於當前組件。

class Clock extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			date : new Date()
		}
	}
	componentDidMount() {
		//這裏是Clock組件第一次被渲染到DOM時會調用,也就是掛載
	}
	
	componentWillUnmount() {
		//當DOM組件Clock被刪除時,會調用,也就是卸載
	}
	render(){
		return (
			<div>
				<h1>Hello, World</h1>
				<h2>It's {this.state.date.toLocaleTimeString()}</h2>
			</div>
		)
	}
}

修改state中數據:

class Clock extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			date: new Date()
		}
	}
	componentDidMount() {
		//這裏是Clock組件第一次被渲染到DOM時會調用,也就是掛載
		this.timer = setInterval(()=>{
			this.tick()
		},1000)
	}
	
	tick(){
		this.setState({
			date: new Date()
		})
	}
	
	componentWillUnmount() {
		//當DOM組件Clock被刪除時,會調用,也就是卸載
		clearInterval(this.timer)
	}
	render(){
		return (
			<div>
				<h1>Hello, World</h1>
				<h2>It's {this.state.date.toLocaleTimeString()}</h2>
			</div>
		)
	}
}

不要直接修改 State,構造函數是唯一可以給 this.state 賦值的地方

this.setState({name: 'World'})

State 的更新可能是異步的,要解決這個問題,可以讓setState接受一個函數而不是一個對象,這個函數用上一個 state 作爲第一個參數,將此次更新被應用時的 props 做爲第二個參數:

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

事件處理

React 事件的命名採用小駝峯式(camelCase),而不是純小寫。
使用 JSX 語法時你需要傳入一個函數作爲事件處理函數,而不是一個字符串。
在 React 中一個不同點是你不能通過返回 false 的方式阻止默認行爲。你必須顯式的使用 preventDefault 。例如,傳統的 HTML 中阻止鏈接默認打開一個新頁面,你可以這樣寫:

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

在 React 中,可能是這樣的:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

class函數中綁定this

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // 此語法確保 `handleClick` 內的 `this` 已被綁定。
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}

在循環中,通常我們會爲事件處理函數傳遞額外的參數

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

列表和key

function ListItem(props) {
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <ListItem key={number.toString()}  value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

語法

在 JSX 中所有的屬性都要更換成駝峯式命名,比如 onclick 要改成 onClick,唯一比較特殊的就是 class,因爲在 JS 中 class 是保留字,我們要把 class 改成 className 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章