我的react學習

2022-07-09 18:30:15 字數 2768 閱讀 1507

);

};// 遍歷輸出item

getlist()

// 動態改變輸入框的值

inputchang( e )

// 新增item

additem()

// 刪除item

delitem(index)

}// 匯出todolist

export default todolist;

認識jsx

簡單的jsx的語法

...

render()

<>

新增);

};...

在jsx中只能有乙個根標籤,使用<>(幽靈標籤)包裹,既能滿足jsx的語法格式,在瀏覽器解析時不會解析幽靈標籤,減少了dom樹結構節點,也可以使用**片段(fragments ),效果和<>相同,只是fragments 還有更廣泛的使用,後面會有詳細說明

在jsx中使用注釋,多行使用,單行使用

// 多行

// 單行

在jsx中使用元件的變數或者方法,使用{}包裹

在jsx中繫結的方法預設this指向undefined,所以需要使用bind繫結this的指向

// 方式1: 在constructor指定this

constructor(props)

this.getlist = this.getlist.bind(this)

this.inputchang = this.inputchang.bind(this)

this.additem = this.additem.bind(this)

this.delitem = this.delitem.bind(this)

}// 方式2:繫結事件的時候指定this

......

元件的基本通訊

最簡單的 父 ---> 子 傳值

// 父元件通過在子元件標籤上設定屬性傳遞資料

// 子元件通過this.props獲取父元件傳遞的資料

// this.props.teachername 獲取老師的名稱

render(),我的老師是,

我對老師很

this.props.say(this.state.boyname,"滿意") } >滿意)

}

最簡單的 子 ---> 父 通訊

// 父元件通過在子元件標籤上設定屬性傳遞資料

// 子元件通過this.props獲取父元件傳遞的資料

// this.props.say 獲取父元件提供的方法,通過呼叫父元件的方法,將傳遞的資料作為引數傳入,當父元件的方法被呼叫,就通過獲取當前方法引數的方式,得到了子元件傳遞的資料

render(),

我對老師很

this.props.say(this.state.boyname,"滿意") } >滿意)

}

最簡單的非父子通訊

核心思路:找到共同的父元件,同時使用父元件傳遞的值和方法

過程有些複雜,這裡省略了

teacher.js

import react, from "react"

// 匯入 boy(男孩) 和 girl(女孩) 元件

import boy from "./boy"

import girl from "./girl"

export default class teacher extends component

this.stusay = this.stusay.bind(this);

this.boysaysecret = this.boysaysecret.bind(this);

this.grilsaysecret = this.grilsaysecret.bind(this);

}render()

return (

<>

我是老師

對我很) : " "})

}stusay(stuname,stusaycontent)})}

boysaysecret(constent)})}

grilsaysecret(constent)})}

}

boy.js

import react, from "react"

export default class boy extends component

}render(),我的老師是,

我對老師很

this.props.say(this.state.boyname,"滿意") } >滿意,

我想對女孩說:this.props.boysaysecret("我喜歡你")}>悄悄話,

她對我說:)}

}

gril.js

import react, from "react"

export default class boy extends component

}render(),我的老師是,

我對老師很

this.props.say(this.state.girlname,"不滿意") } >

不滿意,

我想對男孩說:this.props.grilsaysecret("我也是")}>悄悄話,

他對我說:)}

}

待續....

react學習六 react路由

react router 安裝包yarn add react router dom匯入路由模組 import reactdom from react dom route 表示乙個路由規則,在 route 上,有兩個比較重要的屬性,path component link 表示乙個路由的鏈結 就好比 v...

React的學習(下)

本文接著上篇文章繼續講解react的基礎語法 文字輸入框的值,不能用 this.props.value 讀取,而要定義乙個 onchange 事件的 函式,通過 event.target.value 讀取使用者輸入的值。textarea 元素 select元素 radio元素都屬於這種情況,更多介紹...

React 學習01 React 的基本使用

在使用 react 之前,我們先來了解一下,react 和 vue 一樣是一款 js 庫,他們和 jquery 之類的主要區別是,他們提供了一種解決問題的思路 元件化,而 jquery 只提供了解決問題的方法。所以我們更傾向於稱 react 和 vue 為框架。另外,react 和 vue 的區別是...