日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

React框架的学习

發布時間:2024/1/18 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 React框架的学习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前端-React框架

  • 一、環境搭建
    • 使用 create-react-app 快速構建 React 開發環境
  • 二、react目錄以及文件
    • 目錄結構
    • 組件基礎模板
  • 三、React的知識點
    • 1.JSX語法
      • 自定義屬性
      • 樣式
      • 數組
    • 2.生命周期
    • 3.事件處理
      • 阻止默認行為
      • this指向
      • 函數傳參
    • 4.Context(上下文)
      • API
    • 5.組件API
      • 設置狀態:setState
      • 替換狀態:replaceState
      • 設置屬性:setProps
      • 替換屬性:replaceProps
      • 強制更新:forceUpdate
      • 獲取DOM節點:findDOMNode
      • 判斷組件掛載狀態:isMounted
    • 6.state(狀態)
      • 處理多個state的輸入
    • 7.組件
    • 8.props
  • 四、小案例
    • 效果展示
    • 源碼

什么是 React ?

  • React是一個聲明式的,高效的,并且靈活的用于構建用戶界面的 JavaScript 庫

一、環境搭建

使用 create-react-app 快速構建 React 開發環境

create-react-app 是來自于 Facebook,通過該命令我們無需配置就能快速構建 React 開發環境。

create-react-app 自動創建的項目是基于 Webpack + ES6 。

執行以下命令創建項目:

-- 安裝create-react-app腳手架 npm install -g create-react-app -- 創建項目 my-app create-react-app my-app -- 進入到項目目錄 cd testdemo -- 運行項目 npm start

瀏覽器打開http://localhost:3000/,出現以下畫面即為運行成功


二、react目錄以及文件

目錄結構


組件基礎模板


三、React的知識點

1.JSX語法

class ShoppingList extends React.Componnet {// 虛擬DOMrender() {return (<div className="shopping-list"><h1>Shoping List for {this.props.name}</h1><ul><li>Instagram</li><li>WhatApp</li><li>Oculus</li></ul></div>)} }

在這里,ShoppingList是一個 React組件類,或 React組件類型。組件接受參數,稱為屬性 props, 并通過 render方法返回一個現實的視圖層次結構。

render 方法返回要渲染的內容描述,然后React接受該描述并將其渲染到屏幕上

注意:
由于 JSX 就是 JavaScript,一些標識符像 class 和 for 不建議作為 XML 屬性名。作為替代,React DOM 使用 className 和 htmlFor 來做對應的屬性。


自定義屬性

實例中的 p 元素添加了自定義屬性 data-myattribute,添加自定義屬性需要使用 data- 前綴。

ReactDOM.render(<div><p data-myattribute="somevalue">自定義屬性</p></div>,document.getElementById('example') );

樣式

React 推薦使用內聯樣式。
我們可以使用 camelCase 語法來設置內聯樣式. React 會在指定元素數字后自動添加 px 。以下實例演示了為 h1 元素添加 myStyle 內聯樣式:

var myStyle = {fontSize: 100,color: '#FF0000' }; ReactDOM.render(<h1 style={myStyle}>菜鳥教程</h1>,document.getElementById('example') );

數組

JSX 允許在模板中插入數組,數組會自動展開所有元素:

var arr = [<h1>菜鳥教程</h1>,<h2>學的不僅是技術,更是夢想!</h2>, ]; ReactDOM.render(<div>{ arr }</div>,document.getElementById('example') );

2.生命周期

  • componentWillMount:在渲染前調用,在客戶端也在服務端。

  • componentDidMount ::在第一次渲染后調用,只在客戶端。

  • componentWillReceiveProps:在組件接收到一個新的 prop (更新后)時被調用。這個方法在初始化render時不會被調用。

  • shouldComponentUpdate:返回一個布爾值。在組件接收到新的props或者state時被調用。在初始化時或者使用forceUpdate時不被調用。

  • componentWillUpdate:在組件接收到新的props或者state但還沒有render時被調用。在初始化時不會被調用。

  • componentDidUpdate:在組件完成更新后立即調用。在初始化時不會被調用。

  • componentWillUnmount:在組件從 DOM 中移除之前立刻被調用。

react生命周期函數詳細


3.事件處理

阻止默認行為

在 React 中不同的是你不能使用return false 的方式阻止默認行為, 你必須明確使用 preventDefault

在 React 的寫法為:

function ActionLink() {function handleClick(e) {e.preventDefault();console.log('鏈接被點擊');}return (<a href="#" onClick={handleClick}>點我</a>); }

this指向

react中,類的方法默認是不會綁定 this 的。如果你忘記綁定 this.handleClick 并把它傳入 onClick, 當你調用這個函數的時候 this 的值會是 undefined。

export default class Test extends Component {constructor(props) {super(props)// 該處是為了綁定當前實例對象this.testClick3 = this.testClick3.bind(this)}// 沒有做任何綁定testClick() {console.log(this) // 打印 undefined}// 箭頭函數testClick2 = () => {console.log(this) // 打印 當前實例對象}// 通過 constructor 中的 bind 綁定 thistestClick3() {console.log(this) // 打印 當前實例對象}testClick4() {console.log(this) // 打印 當前實例對象}render() {return (<><button onClick={this.testClick}>click1</button><button onClick={this.testClick2}>click2</button><button onClick={this.testClick3}>click3</button>{/* 箭頭函數 => 打印 當前實例對象 */}<button onClick={() => this.testClick3()}>click4</button></>)} }

函數傳參

通過 bind:

  • 函數名.bind(參數, Event)

通過 箭頭函數:

  • (Event) => 函數名(參數, Event)
export default class Test extends Component {constructor() {super()this.state = { name: 'Hello world!' }}// e: 打印事件對象 | name: Hello world!testClick(name, e) {console.log(e)console.log(name)}render() {return (<>{/* 使用bind傳參,第一個參數是 事件對象, 第二個才是 方法所需參數 */}<button onClick={this.testClick.bind(this, this.state.name)}>click1</button>{/* 使用箭頭函數傳參,(e) 是事件對象,不傳入的話,方法打印出來的 e 是 undefined */}<button onClick={(e) => this.testClick(this.state.name, e)}>click2</button></>)} }

4.Context(上下文)

Context 通過組件樹提供了一個傳遞數據的方法,從而避免了在每一個層級手動的傳遞 props 屬性


API

(1)React.createContext:創建一個上下文的容器(組件), defaultValue可以設置共享的默認數據

const {Provider, Consumer} = React.createContext(defaultValue);

(2)Provider(生產者): 和他的名字一樣。用于生產共享數據的地方。生產什么呢? 那就看value定義的是什么了。value:放置共享的數據。

<Provider value={/*共享的數據*/}>/*里面可以渲染對應的內容*/ </Provider>

(3)Consumer(消費者):這個可以理解為消費者。 他是專門消費供應商( Provider)產生數據。Consumer需要嵌套在生產者下面。才能通過回調的方式拿到共享的數據源。當然也可以單獨使用,那就只能消費到上文提到的defaultValue

<Consumer>{value => /*根據上下文 進行渲染相應內容*/} </Consumer>

5.組件API

設置狀態:setState

setState(object nextState[, function callback])

參數說明

  • nextState,將要設置的新狀態,該狀態會和當前的state合并
  • callback,可選參數,回調函數。該函數會在setState設置成功,且組件重新渲染后調用。

合并nextState和當前state,并重新渲染組件。setState是React事件處理函數中和請求回調函數中觸發UI更新的主要方法。

關于setState
不能在組件內部通過this.state修改狀態,因為該狀態會在調用setState()后被替換。

setState()并不會立即改變this.state,而是創建一個即將處理的state。setState()并不一定是同步的,為了提升性能React會批量執行state和DOM渲染。

setState()總是會觸發一次組件重繪,除非在shouldComponentUpdate()中實現了一些條件渲染邏輯。


替換狀態:replaceState

replaceState(object nextState[, function callback])
  • nextState,將要設置的新狀態,該狀態會替換當前的state
  • callback,可選參數,回調函數。該函數會在replaceState設置成功,且組件重新渲染后調用。

**replaceState()方法與setState()**類似,但是方法只會保留nextState中狀態,原state不在nextState中的狀態都會被刪除。

設置屬性:setProps

setProps(object nextProps[, function callback])
  • nextProps,將要設置的新屬性,該狀態會和當前的props合并
  • callback,可選參數,回調函數。該函數會在setProps設置成功,且組件重新渲染后調用。
    設置組件屬性,并重新渲染組件。

props相當于組件的數據流,它總是會從父組件向下傳遞至所有的子組件中。當和一個外部的JavaScript應用集成時,我們可能會需要向組件傳遞數據或通知React.render()組件需要重新渲染,可以使用setProps()

更新組件,我可以在節點上再次調用React.render(),也可以通過**setProps()**方法改變組件屬性,觸發組件重新渲染。


替換屬性:replaceProps

replaceProps(object nextProps[, function callback])
  • nextProps,將要設置的新屬性,該屬性會替換當前的props
  • callback,可選參數,回調函數。該函數會在replaceProps設置成功,且組件重新渲染后調用。
    replaceProps()方法與setProps()類似,但它會刪除原有 props。

強制更新:forceUpdate

forceUpdate([function callback])

參數說明

  • callback,可選參數,回調函數。該函數會在組件**render()**方法調用后調用。

forceUpdate()方法會使組件調用自身的render()方法重新渲染組件,組件的子組件也會調用自己的render()。但是,組件重新渲染時,依然會讀取this.props和this.state,如果狀態沒有改變,那么React只會更新DOM。

forceUpdate()方法適用于this.props和this.state之外的組件重繪(如:修改了this.state后),通過該方法通知React需要調用render()

一般來說,應該盡量避免使用forceUpdate(),而僅從this.props和this.state中讀取狀態并由React觸發render()調用。


獲取DOM節點:findDOMNode

DOMElement findDOMNode()
  • 返回值:DOM元素DOMElement

如果組件已經掛載到DOM中,該方法返回對應的本地瀏覽器 DOM 元素。當render返回nullfalse時,this.findDOMNode()也會返回null。從DOM 中讀取值的時候,該方法很有用,如:獲取表單字段的值和做一些 DOM 操作。


判斷組件掛載狀態:isMounted

bool isMounted()
  • 返回值:true或false,表示組件是否已掛載到DOM中

isMounted()方法用于判斷組件是否已掛載到DOM中。可以使用該方法保證了setState()和forceUpdate()在異步場景下的調用不會出錯。


以上參考:https://www.runoob.com/react/react-component-api.html

6.state(狀態)

React 把組件看成是一個狀態機(State Machines)。通過與用戶的交互,實現不同狀態,然后渲染 UI,讓用戶界面和數據保持一致。

React 里,只需更新組件的 state,然后根據新的 state 重新渲染用戶界面(不要操作 DOM)。

export default class Test extends Component {// constructor用于給state綁定實例constructor(props) {super(props)// 設置statethis.state = {msg: 'test msg',msg2: 'setState msg',}}// 上下兩段都可用于設置state,但不能一起使用// state = {// msg2: 'test2 msg',// }render() {return (<>{/* 獲取state */}{this.state.msg}<buttononClick={() => {this.state.msg = 'new test msg'// 當改變了state時,不會主動更新,需要調用this.setState()來讓頁面渲染,重新加載render()// this.setState()會更新當前頁面所有的state,可以不用像msg2一樣重復設置this.setState({msg2: 'setState msg',})}}>click</button>{/* {this.state.msg2} */}</>)} }

處理多個state的輸入

export default class Test extends Component {constructor() {super()this.state = {id: '1',name: '小明',sex: '男',tableList: {age: '22',height: '180cm',},}}// 處理多個輸入// input 中的 name屬性 要跟 state 的鍵對應// 處理多個inputhandleInputChange(e) {const target = e.targetlet name = target.namethis.setState({[name]: target.value,})}// 處理表單中的input值_handleInputChange(e) {const target = e.targetlet name = target.namelet value = target.valueconst tableList = this.state.tableListtableList[name] = valuethis.setState({tableList,})}render() {return (<>{this.state.id}<br />{this.state.name}<br />{this.state.sex}<br />{this.state.tableList.age}<br />{this.state.tableList.height}<form>id:<inputname="id"value={this.state.id}onChange={(e) => this.handleInputChange(e)}/><br />name:<inputname="name"value={this.state.name}onChange={(e) => this.handleInputChange(e)}/><br />sex:<inputname="sex"value={this.state.sex}onChange={(e) => this.handleInputChange(e)}/><br />age:<inputname="age"value={this.state.tableList.age}onChange={(e) => this._handleInputChange(e)}/><br />height:<inputname="height"value={this.state.tableList.height}onChange={(e) => this._handleInputChange(e)}/></form></>)} }

以上處理參考:https://www.cnblogs.com/xfswy/p/14980918.html


7.組件

// class組件 export default class Test extends Component {render() {return (<><button onClick={(e) => { console.log(e) }}>Test1 click</button>{/* 展開Test2,并傳遞子節點<h1> */}<Test2><h1>展開hello world</h1></Test2></>)} }// 函數式組件 // 該函數是一個有效的 React 組件,因為它接收唯一帶有數據的 “props”(代表屬性) // 對象與并返回一個 React 元素。這類組件被稱為“函數組件”,因為它本質上就是 JavaScript 函數。 const Test2 = (props) => {function welcome(e) {console.log(e)console.log('hello world')}return (<div><button onClick={(e) => welcome(e)}>Test2 click</button>{/* 獲取傳遞來的子節點 */}{props.children}</div>) }

8.props

state 和 props 主要的區別在于 props 是不可變的,而 state 可以根據與用戶交互來改變。這就是為什么有些容器組件需要定義 state 來更新和修改數據。 而子組件只能通過 props 來傳遞數據。

// 函數式組件 // 這里是通過傳參獲取props,所以不需要使用this const Test2 = (props) => <div>{props.msg2}</div>// ES6 class關鍵字 定義 class Test3 extends Component {render() {// 這里是通過this訪問當前實例獲取propsreturn <div>{this.props.msg3}</div>} }class Test4 extends Component {// 通過靜態屬性 defaultProps 給props設置默認值static defaultProps = {msg4: 'default msg4',}render() {return <div>{this.props.msg4}</div>} }// 下方代碼等價于上面Test4中的 static defaultProps Test4.defaultProps = {msg4: 'new default msg4', }export default class Test extends Component {render() {return (<><Test2 msg2="test msg2" /><Test3 msg3="test msg3" /><Test4 /></>)} }

四、小案例

涉及以下知識點的使用

  • state:狀態保持以及更新
  • 函數、事件處理
  • 列表循環
  • 條件渲染

效果展示

源碼

寫的很亂,看看就行
組件 home.js

import React, { Component } from 'react' import './Home.css'class Home extends Component {constructor(props) {super(props)this.state = {// 原始數據tableList: [{id: '031',name: '小明',sex: '男',age: '12',height: '180',weight: '79',birthday: '1922-10-20',},{.............}],// 是否顯示詳細數據界面isShowDetailed: false,// 是否顯示修改數據界面isShowEdit: false,// 詳細數據表detailedItem: {},// 當前修改數據的key值editKey: null,// 修改數據界面模板以及存儲當前需修改的數據editItem: {id: '1',name: '1',sex: '',age: '',height: '',weight: '',birthday: '',},}// 為函數綁定當前對象,讓函數可以獲取到thisthis.changeData = this.changeData.bind(this)}// 顯示詳細數據showData = (data) => {this.setState({isShowDetailed: true,detailedItem: data,})}// 隱藏詳細數據hideData = () => {this.setState({isShowDetailed: !this.state.isShowDetailed,})}// 顯示修改數據showEdit = (key) => {this.setState({isShowEdit: true,editItem: this.state.tableList[key],editKey: key,},() => {let inputs = document.getElementById('editId').getElementsByTagName('input')for (let i = 0; i < inputs.length; i++) {let key = Object.keys(this.state.editItem)inputs[i].value = this.state.editItem[key[i]]}})}// 隱藏修改數據hideEdit = () => {this.setState({isShowEdit: !this.state.isShowEdit,})}// 修改數據 changeData() {let data = this.state.tableListdata[this.state.editKey] = {id: document.getElementById('id').value,name: document.getElementById('name').value,sex: document.getElementById('sex').value,age: document.getElementById('age').value,height: document.getElementById('height').value,weight: document.getElementById('weight').value,birthday: document.getElementById('birthday').value,}this.setState({editItem: this.state.tableList[this.state.editKey],isShowEdit: !this.state.isShowEdit,isShowDetailed: !this.state.isShowDetailed,})}// 刪除數據deleteData(key) {this.state.tableList.splice(key, 1)this.setState({isShowDetailed: false,isShowEdit: false,})}// 虛擬DOMrender() {return (<div className="home"><h1>調查</h1><table><tbody><tr><th></th><th>id</th><th>名稱</th><th>性別</th><th>年齡</th><th>操作</th></tr>{this.state.tableList.map((item, key) => {return (<tr key={item.id}><td>{key + 1}</td><td>{item.id}</td><td>{item.name}</td><td>{item.sex}</td><td>{item.age}</td><td><buttonclassName="info"onClick={this.showData.bind(this, item)}>詳細數據</button><buttonclassName="warning"onClick={this.showEdit.bind(this, key)}>編輯</button><buttonclassName="danger"onClick={this.deleteData.bind(this, key)}>刪除</button></td></tr>)})}</tbody></table><divclassName="detailed"style={{ display: this.state.isShowDetailed ? 'block' : 'none' }}><span>詳細數據:</span><table><tbody><tr><th>id</th><th>名稱</th><th>性別</th><th>年齡</th><th>身高(cm)</th><th>體重(kg)</th><th>生日</th><th>操作</th></tr><tr>{Object.keys(this.state.detailedItem).map((obj, idx) => {return <td key={idx}>{this.state.detailedItem[obj]}</td>})}<td><buttonclassName="danger"onClick={this.hideData}title="關閉表單">X</button></td></tr></tbody></table></div><divclassName="edit"id="editId"style={{ display: this.state.isShowEdit ? 'block' : 'none' }}><span>編輯數據:</span><table><tbody><tr><th>id</th><th>名稱</th><th>性別</th><th>年齡</th><th>身高(cm)</th><th>體重(kg)</th><th>生日</th><th>操作</th></tr><tr>{Object.keys(this.state.editItem).map((obj, idx) => {return (<td key={idx}><input id={obj} /></td>)})}<td><button className="smbit" onClick={this.changeData}>確認</button><buttonclassName="danger"onClick={this.hideEdit}title="關閉表單">X</button></td></tr></tbody></table></div></div>)} }export default Home

以上為個人筆記,不代表絕對正確,有錯誤還請幫忙指正

總結

以上是生活随笔為你收集整理的React框架的学习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。