目前主流的框架有react/angular/vue蔫慧。與angular不同蟀架,react是專注于用戶界面構(gòu)建寝蹈,也就是mvvm中的view層,數(shù)據(jù)層(Model)和控制層(ViewModel)則是由社區(qū)提供的庫進行構(gòu)建侄非。在寫react的時候蕉汪,記住一點:react就是js流译。
react腳手架
npm install -g create-react-app
--安裝腳手架
create-react-app my-app
--使用腳手架創(chuàng)建react項目
cd my-app
--進入指定項目
npm start
--啟動項目
react基礎(chǔ)知識
jsx簡介
const element = <h1>Hello, world!</h1>;
如上變量,被成為JSX語言者疤,是javascript的語法擴展福澡,Babel會把JSX轉(zhuǎn)譯成React.createElement函數(shù)調(diào)用。以下2種方式等價
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element=React.createElement(
'h1',
{className:'greeting'},
''Hello World!
)
- jsx使用
聲明一個變量name驹马,在JSX中使用,寫在大括號中竞漾。在 JSX 語法中,你可以在大括號內(nèi)放置任何有效的 JavaScript 表達式窥翩。例如业岁,2 + 2
,user.firstName
或formatName(user)
都是有效的 JavaScript 表達式寇蚊。
const element=<p onClick={this.changeName} className='zhangsan' style={{coloe:red}}>{name}</p>
在下面的示例中笔时,我們將調(diào)用 JavaScript 函數(shù) formatName(user) 的結(jié)果,并將結(jié)果嵌入到 <h1> 元素中仗岸。
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
組件
react的核心就是組件允耿,react組件分為函數(shù)類型組件和基于類的組件2種類型
函數(shù)類型的組件就是使用function創(chuàng)建的組件,基于類的組件是使用class關(guān)鍵詞創(chuàng)建的組件扒怖,組件的本質(zhì)也是函數(shù)较锡。在react中組件名稱以大寫字母開頭。
- 函數(shù)式組件寫法
function Welcome1(props) {
return <div>Welcome1, {props.name}</div>;
}
- 基于類的組件寫法
class Welcome2 extends React.Component {
render() {
return <div>Welcome2, {this.props.name}</div>;
}
}
- 組件的調(diào)用
class Welcome2 extends React.Component {
render() {
return <Welcome1 name='張三'></Welcome1>;
}
}
state和props
在react中是單向數(shù)據(jù)流盗痒,頂級組件就有狀態(tài)state蚂蕴,通過props向下級組件進行傳遞。下級組件為無狀態(tài)組件俯邓,只能使用props骡楼,不能夠修改狀態(tài)。在組件中稽鞭,不能直接修改state鸟整,只能通過setState進行修改組件狀態(tài)。組件狀態(tài)的修改是異步的朦蕴,多次調(diào)用會合并成一次進行組件狀態(tài)的修改篮条。因此如果需要連續(xù)多次的修改狀態(tài)可以使用以下寫法
this.setState(()=>{
date:new Date()
})
import React, { Component } from "react";
export default class StateTest extends Component {
state = {
counter: 1
};
componentDidMount() {
// 請不要直接修改狀態(tài)值
// this.state.counter += 1;
// 2.批量執(zhí)行
// this.setState(obj, cb)
// this.setState(fn, cb)
this.setState(prevState => ({
counter: prevState.counter + 1
}));
this.setState(prevState => ({
counter: prevState.counter + 1
}));
this.setState(prevState => ({
counter: prevState.counter + 1
}));
}
render() {
return <div>{this.state.counter}</div>;
}
}
組件的嵌套
組件的嵌套以購物車的實例來進行說明。直接上代碼吩抓。
- 將函數(shù)和組件狀態(tài)以props的形式傳入下級組件涉茧。下級組件均為無狀態(tài)組件,只負責渲染琴拧,邏輯均在頂層組件
- 函數(shù)的綁定與DOM不同的點在于降瞳,在DOM中綁定函數(shù)名小寫,在react中是駝峰命名法蚓胸。在DOM中函數(shù)傳入字符串挣饥,在react中傳入函數(shù)體。
- 在react的使用中沛膳,由于this指向問題扔枫,在定義函數(shù)時,盡量使用箭頭函數(shù)的方式進行定義
reduceShopBook=()=>{}
這樣this的指向f方為react實例锹安。
或者在初始化組件時短荐,使用以下方式來改變this指向
this.reduceShopBook=this.reduceShopBook.bind(this)
- 在jsx中可以map來循環(huán)數(shù)組
- 在react中可以使用條件判斷和三元表達式來確定渲染的元素和組件。
// 三元表達式
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
// 使用If條件判斷
const isLoggedIn = this.state.isLoggedIn;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component{
constructor(){
super();
this.reduceShopBook=this.reduceShopBook.bind(this)
}
state={
books:[{
name:'javascrip語言精粹',
id:'1'
},{
name:'javascript高級程序設(shè)計',
id:'2'
}],
shopBooks:[
{
name:'javascrip語言精粹',
id:'1',
count:1
}
]
}
// 減少數(shù)目
reduceShopBook(bookItem){
const shopBooks=[...this.state.shopBooks];
const bookIndex=shopBooks.findIndex((book)=>bookItem.id===book.id)
if(shopBooks[bookIndex].count===1){ //去掉選項
shopBooks.splice(bookIndex,1)
}else{
const newBook=Object.assign(shopBooks[bookIndex],{count:shopBooks[bookIndex].count-1})
shopBooks.splice(bookIndex,1,newBook)
}
this.setState({shopBooks:shopBooks})
}
// 增加購物車中數(shù)目
addShopBook=(bookItem)=>{
let shopBooks=[...this.state.shopBooks];
const bookIndex=shopBooks.findIndex((book)=>bookItem.id===book.id)
if(bookIndex===-1){
bookItem.count=1
shopBooks=[...shopBooks,bookItem]
}else{
const book=Object.assign(shopBooks[bookIndex],{count:shopBooks[bookIndex].count+1})
}
this.setState({shopBooks:shopBooks})
}
// 渲染叹哭,調(diào)用下級組件忍宋。 將函數(shù)和組件狀態(tài)以props的形式傳入下級組件。修改組
render(){
const bookItems=<BookList books={this.state.books} addShopCart={this.addShopBook}></BookList>
const shopcart=<Shopcart shopBooks={this.state.shopBooks} addShopBook={this.addShopBook} reduceShopBook={this.reduceShopBook}></Shopcart>
const footer=<input type='button' value='確定' />
return <div>
{bookItems}
{shopcart}
</div>
}
}
export default App;
/**
* 書本列表 組件使用函數(shù)式組件风罩,在下級組件中使用函數(shù)式組件糠排,寫法較為簡單。
* @param {*} props
*/
function BookList(props){
const listItems= props.books.map((bookItem)=>{
return <li key={bookItem.id}>{bookItem.name} <input type='button' value='加入購物車' onClick={e=>props.addShopCart(bookItem)} /></li>
})
return <ul>{listItems} </ul>
}
/**
* 購物車列表
* @param {} props
*/
function Shopcart(props){
const shopItems=props.shopBooks.map((bookItem)=>{
return <tr>
<td>{bookItem.name}</td>
<td>{bookItem.count}</td>
<td><input type="button" value="+" onClick={e=>props.addShopBook(bookItem)} /><input type='button' value='-' onClick={e=>props.reduceShopBook(bookItem)}/></td>
</tr>
})
return <table>
<thead><th>名稱</th><th>數(shù)目</th><th>操作</th></thead>
{shopItems}
</table>
}
}
React中children的使用
有人說超升,咦入宦,類似于vue中slot,在react中怎么沒有室琢?不急乾闰,使用react中使用children屬性可實現(xiàn)哦。
- React中的Children不一定是組件盈滴,它們可以使任何東西涯肩。從本質(zhì)上來講, props.children 可以使任何的類型巢钓,比如數(shù)組宽菜、函數(shù)、對象等等竿报。
- React提供了一系列的函數(shù)助手來使得操作children更加方便铅乡。
兩個最顯眼的函數(shù)助手就是 React.Children.map 以及 React.Children.forEach 。它們在對應數(shù)組的情況下能起作用烈菌,除此之外阵幸,當函數(shù)、對象或者任何東西作為children傳遞時芽世,它們也會起作用挚赊。 - 直接來個例子,封裝一個彈出框济瓢,外層樣式統(tǒng)一定義荠割,內(nèi)容和樣式可定義。封裝一個過濾器
// 容器類組件 不需要知道狀態(tài)
// 作為容器 不需要關(guān)心狀態(tài)和邏輯
function Dialog(props){
return <div style={{border:`1px solid ${props.color||'blue'}`}}>
{props.children}
{props.footer}
</div>
}
// 使用封裝好的彈出框
function WelcomeDialog(props){
return <Dialog {...props}>
<p>hello world</p>
</Dialog>
}
// 過濾器
function Filter(props){
return<div>
{
React.Children.map(props.children,(element)=>{
if(element.type===props.type){
return element
}
})
}
</div>
}
class App extends React.Component{
render(){
const footer=<input type='button' value='確定' />
return <div>
<WelcomeDialog color="green" footer={footer}></WelcomeDialog>
<Filter type='p'>
<p>1、p標簽的使用</p>
<span>2蔑鹦、span標簽</span>
</Filter>
</div>
}
}
}