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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

react map循环生成的button_关于Vue和React的一些对比及个人思考(中)

發(fā)布時間:2023/12/19 vue 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 react map循环生成的button_关于Vue和React的一些对比及个人思考(中) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

vue和React都是目前最流行、生態(tài)最好的前端框架之一。框架本身沒有優(yōu)劣之分,只有適用之別,選擇符合自身業(yè)務(wù)場景、團隊基礎(chǔ)的技術(shù)才是我們最主要的目的。

博主1年前用的是Vue框架,近半年轉(zhuǎn)技術(shù)棧到React框架,對于Vue和React都有一些基本的了解。接下來博主將與大家通過上、中、下三部一起走近Vue和React,共同探討它們的差異。(比如你正在用vue,對react感興趣也可以看下,反之亦然)

整體內(nèi)容概覽:

中部將主要從條件渲染是否顯示列表渲染計算屬性偵聽器ref表單插槽八個方面對比vue和react,歡迎多多交流,共同探討,感謝支持。

上部鏈接:關(guān)于Vue和React的一些對比及個人思考(上)

9.條件渲染(v-if vs &&)

條件渲染用于根據(jù)條件判斷是否渲染一塊內(nèi)容。

vue

vue中用v-if指令條件性地渲染一塊內(nèi)容。只有當表達式返回真值時才被渲染,v-if還可以和v-else-if、v-else配合使用,用于不同條件下的渲染,類似js里的if else語法。

(1)基本用法

This is content.復制代碼

data

data() { return { showContent: false } }復制代碼

當showContent為false時,不會渲染DOM節(jié)點,會留下一個注釋標志。

showContent為true時,才會渲染DOM節(jié)點。

(2)v-else 二重判斷

v-if和v-else配合使用時,v-else必須要和v-if相鄰,否則會報錯。

This is content. Hide content. 復制代碼

(3)v-else-if 多重判斷

當有多重判斷條件時,可以使用v-else-if,類似v-if的else-if塊,v-else 元素必須緊跟在帶v-if或者v-else-if的元素的后面,否則它將不會被識別。

A B C Not A/B/C復制代碼

(4)template 使用 v-if

另外,當想切換多個元素時,在上使用v-if可以針對元素進行分組。

Title

Paragraph 1

Paragraph 2

復制代碼

react

react使用與運算符&&、三目運算符(?:)、if else來實現(xiàn)條件渲染的效果。

(1)與運算符

與運算符&&,實現(xiàn)效果類似v-if,左邊變量為真值時,渲染右邊的元素。

return ( {showItem && This is content.} );復制代碼

(2)三目運算符(?:)

使用三目運算符(?:),實現(xiàn)類似v-if v-else效果,showItem變量為true時顯示第一個元素,變量為false時顯示第二個元素。

return ( { showItem ? (This is true content.) : (This is false content.) } );復制代碼

(3)多重判斷

當處理多重判斷時,可以使用函數(shù)加if else多重判斷或者switch case的形式來實現(xiàn),實現(xiàn)類似v-if v-else-if v-else的效果。

Ⅰ.if-else多重判斷

render() { const { type } = this.state; const toggeleShow = (type) => { if (type === 'A') { return A; } else if (type === 'B') { return B; } else if (type === 'C') { return C; } else { return null; } }; return ( {toggeleShow(type)} ); }復制代碼

Ⅱ.switch case多重判斷

render () { const { type } = this.state; const toggeleShow = (type) => { switch (type) { case 'A': return A; case 'B': return B; case 'C': return C; default: return null; } }; return ( {toggeleShow(type)} ); }復制代碼

10.是否顯示(v-show vs style+class)

另一個用于展示條件的元素的選項是v-show,react中可以通過style或者切換class的形式實現(xiàn)是否顯示。

vue

v-show渲染的元素會被渲染并保留在DOM中。v-show只是簡單地切換元素的css屬性display。

This is content.復制代碼

showContent為false時,style的display屬性值為none。

showContent為true時,style的display屬性值為block(元素默認display屬性值)。

注意,v-show 不支持 元素,也不支持 v-else。

v-if與v-show對比總結(jié):

  • 1)v-if是“真正”的條件渲染,因為它會確保在切換過程中條件塊內(nèi)的事件監(jiān)聽器和子組件適當?shù)乇讳N毀和重建。
  • 2)v-if也是惰性的:如果在初始渲染時條件為假,則什么也不做——直到條件第一次變?yōu)檎鏁r,才會開始渲染條件塊。
  • 3)相比之下,v-show就簡單得多——不管初始條件是什么,元素總是會被渲染,并且只是簡單地基于 CSS 進行切換。
  • 4)一般來說,v-if有更高的切換開銷,而v-show有更高的初始渲染開銷。因此,如果需要非常頻繁地切換,則使用v-show較好;如果在運行時條件很少改變,則使用v-if較好。

react

react中通過修改style或者class來實現(xiàn)v-show類似效果。

通過修改style屬性的display屬性來實現(xiàn)切換是否顯示。

This is content.復制代碼

通過變量判斷修改class來實現(xiàn)切換效果,本質(zhì)上也是切換元素的display屬性來實現(xiàn)切換效果。

在react中動態(tài)修改元素樣式時(比如切換tab、按鈕選中狀態(tài)),適用于使用class來實現(xiàn)。

const itemClass = showItem ? 'show-item-class' : 'hide-item-class'; return ( This is content. );復制代碼

class樣式:

.show-item-class { display: block;}.hide-item-class { display: none;}復制代碼

11.列表渲染(v-for vs map)

vue中使用v-for來渲染列表,react中使用map來渲染列表。不管是v-for還是map來渲染列表都需要添加key值(key在兄弟節(jié)點之間必須唯一),方便快速比較出新舊虛擬DOM樹間的差異。

vue

vue中可以使用v-for來渲染數(shù)組、對象、、組件。

(1)渲染數(shù)組

渲染數(shù)組時,使用(item, index) in items形式的特殊語法,其中items是源數(shù)據(jù)數(shù)組,item則是被迭代的數(shù)組元素的別名,index表示當前元素的索引。

{{item.message}} 復制代碼

data

data() { return { items: [ { message: 'Hello' }, { message: 'Welcome' } ] } }復制代碼

(2)渲染對象

v-for也可以用來遍歷一個對象的屬性,使用(value, key, index) in obj的形式,其中key表示對象的key值,value表示對象的value值,index表示當前索引。

在遍歷對象時,采用Object.keys()的結(jié)果遍歷,但是不能保證它的結(jié)果在不同的 JavaScript 引擎下都一致。

{{index}}.{{key}}: {{value}}復制代碼

data

data() { return { obj: { name: 'xiaoming', age: 18, sex: 'male', height: 175 } } }復制代碼

(3)渲染多個元素

在上使用v-for來渲染一段包含多個元素的內(nèi)容。

在上使用v-for來渲染元素段時,不允許綁定key值。因為template上并不會生成實際Dom節(jié)點。可以給底下的子元素綁定key值。

{{ item.message }} 復制代碼

data

data() { return { items: [ { message: 'hello' }, { message: 'world' }, { message: 'welcome' } ] } },復制代碼

生成DOM時,并不會生成實際DOM節(jié)點。

(4)渲染自定義組件列表

在自定義組件上,可以使用v-for渲染自定義組件列表,通過props將數(shù)據(jù)傳遞給組件。

在組件上使用v-for時,key是必須的。

v-for渲染自定義組件列表,將item通過props傳遞給組件。

復制代碼

my-component組件使用props接收父組件傳來的數(shù)據(jù)。

{{item.message}}復制代碼

react

react中使用map()方法來實現(xiàn)列表渲染。

(1)渲染數(shù)組

遍歷數(shù)組中的每個元素,得到一組jsx元素列表。數(shù)組中的每一個元素需要添加唯一的key值。

render() { const items = [ { message: 'hello' }, { message: 'world' }, { message: 'welcome' } ]; const listItems = items.map((item, index) => {item.message}); return ( {listItems} ); }復制代碼

(2)渲染對象

對于對象,可以采用方法通過Object.keys()或者Object.entries()來遍歷對象。

render() { const obj = { name: 'xiaoming', age: 18, sex: 'male', height: 175 }; const renderObj = (obj) => { const keys = Object.keys(obj); return keys.map((item, index) => {obj[item]}); }; return ( {renderObj(obj)} ); }復制代碼

(3)渲染自定義組件列表

渲染自定義組件列表與vue中類似,需要給組件添加key值標識。

render() { const items = [ { message: 'hello' }, { message: 'world' }, { message: 'welcome' } ]; const listItems = items.map((item, index) => ); return ( {listItems} ); }復制代碼

12.計算屬性(computed vs useMemo+useCallback)

計算屬性表示根據(jù)組件的數(shù)據(jù)(包含組件自身的數(shù)據(jù)和接收父組件的props)需要二次計算并“保存”的數(shù)據(jù),使用計算屬性的好處是避免每次重復計算的開銷(比如遍歷一個巨大的數(shù)組并做大量的計算)。

vue

vue中用computed來表示計算屬性,可以定義多個計算屬性,計算屬性可以互相調(diào)用。計算屬性是基于它們的響應式依賴進行緩存的。只在相關(guān)響應式依賴發(fā)生改變時它們才會重新求值。vue中可以直接使用this.xxx直接獲取到計算屬性。

(1)基本用法

下面聲明計算屬性reversedMessage依賴于message,這就意味著只要 message還沒有發(fā)生改變,多次訪問reversedMessage計算屬性會立即返回之前的計算結(jié)果。

message: {{reversedMessage}}復制代碼

script

data() { return { message:'' } }, computed: { reversedMessage() { return this.message.split('').reverse().join('') } }復制代碼

(2)計算屬性的setter

技術(shù)屬性默認只有g(shù)etter,也可以使用setter,當修改計算屬性的時候,會觸發(fā)setter回調(diào)。

script

data() { return { message:'', info: '' } }, computed: { reversedMessage: { get() { // get回調(diào) return this.message.split('').reverse().join('') }, set(newValue) { // set回調(diào) this.info = newValue } } }, methods: { changeMessage(event) { // 修改reversedMessage計算屬性 this.reversedMessage = event.target.value; } }復制代碼

react

react hooks使用useMemo表示memoized的值,使用useCallback表示memoized的回調(diào)函數(shù),實現(xiàn)與vue中computed類似的功能。

適用場景:子組件使用了PureComponent或者React.memo,那么你可以考慮使用useMemo和useCallback封裝提供給他們的props,這樣就能夠充分利用這些組件的淺比較能力。

(1)useMemo

useMemo返回一個memoized的值。useMemo會依賴某些依賴值,只有在某個依賴項改變時才會重新計算memoized值。如果沒有提供依賴項數(shù)組,useMemo 在每次渲染時都會計算新的值。useMemo可以作為性能優(yōu)化的手段。

傳入useMemo的函數(shù)會在渲染期間執(zhí)行。請不要在這個函數(shù)內(nèi)部執(zhí)行與渲染無關(guān)的操作,諸如副作用這類的操作屬于useEffect的適用范疇,而不是useMemo。

function NewComponent(props) { const { num } = props; const [size, setSize] = useState(0); // max是useMemo返回的一個memoized的值 const max = useMemo(() => Math.max(num, size), [num, size]); return ( setSize(e.target.value)} /> Max {max} );}復制代碼

(2)useCallback

useCallback把內(nèi)聯(lián)回調(diào)函數(shù)及依賴項數(shù)組作為參數(shù)傳入useCallback,它將返回該回調(diào)函數(shù)的memoized版本,該回調(diào)函數(shù)僅在某個依賴項改變時才會更新。當你把回調(diào)函數(shù)傳遞給經(jīng)過優(yōu)化的并使用引用相等性去避免非必要渲染(例如shouldComponentUpdate的子組件時,它將非常有用。

function NewComponent(props) { const [message, setMessage] = useState('hello world.'); const handleChange = useCallback((value) => { setMessage(value); }, []); return ( handleChange(e.target.value)} /> {message} );}復制代碼

13.偵聽器(watch vs getDerivedStateFromProps + componentDidUpdate)

偵聽器是指通過監(jiān)聽props或者組件數(shù)據(jù)(data或state)的變化來執(zhí)行一些異步或者數(shù)據(jù)操作。

vue

vue中主要通過watch監(jiān)聽props、data、computed(計算屬性)的變化,執(zhí)行異步或開銷較大的操作。

下面ProjectManage組件通過watch監(jiān)聽projectId prop的變化獲取對應的項目信息。

export default { name: "ProjectManage", props: ["projectId"], data() { return { projectInfo: null }; }, watch: { projectId(newVaue, oldValue) { if (newVaue !== oldValue) { this.getProject(newValue); } } }, methods: { getProject(projectId) { projectApi .getProject(projectId) .then(res => { this.projectInfo = res.data; }) .catch(err => { this.$message({ type: "error", message: err.message }); }); } }};復制代碼

react

react中通過static getDerivedStateFromProps()和componentDidUpdate()實現(xiàn)監(jiān)聽器的功能。

(1)static getDerivedStateFromProps()

getDerivedStateFromProps會在調(diào)用render方法之前調(diào)用,并且在初始掛載及后續(xù)更新時都會被調(diào)用。它應返回一個對象來更新state,如果返回null則不更新任何內(nèi)容。

關(guān)于getDerivedStateFromProps有2點說明:

  • 1)不管是props變化、執(zhí)行setState或者forceUpdate操作都會在每次渲染前觸發(fā)此方法。
  • 2)當state的值在任何時候都取決于props的時候適用該方法。
class NewComponent extends React.Component { constructor(props) { super(props); this.state = { info: '' } } static getDerivedStateFromProps(nextProps, prevState) { // state中的info根據(jù)props中的info保持同步 if (nextProps.info !== prevState.info) { return { info: nextProps.info } } return null; } render() { const { info } = this.state; return {info} }}復制代碼

(2)componentDidUpdate()

componentDidUpdate()方法在組件更新后被調(diào)用。首次渲染不會執(zhí)行此方法。當組件更新后,可以在此處操作DOM、執(zhí)行setState或者執(zhí)行異步請求操作。

componentDidUpdate(prevProps, prevState, snapshot)復制代碼

關(guān)于componentDidUpdate有4點說明:

  • 1)componentDidUpdate()的第三個參數(shù)snapshot參數(shù)來源于getSnapshotBeforeUpdate()生命周期的返回值。若沒有實現(xiàn)getSnapshotBeforeUpdate(),此參數(shù)值為undefined。
  • 2)可以在componentDidUpdate()中直接調(diào)用setState(),但是它必需被包裹在一個條件語句里,否則會導致死循環(huán)。
  • 3)可以在componentDidUpdate()對更新前后的props進行比較,執(zhí)行異步操作。
  • 4)如果shouldComponentUpdate()返回值為false,則不會調(diào)用componentDidUpdate()。

下面NewComponent組件在componentDidUpdate()里判斷

class NewComponent extends React.Component { constructor(props) { super(props); this.state = { projectInfo: null } } getProject = (projectId) => { projectApi .getProject(projectId) .then(res => { this.projectInfo = res.data; }) .catch(err => { message.error(err.message); }); } componentDidUpdate(prevProps) { if (this.props.projectId !== prevProps.projectId) { this.getProject(this.props.projectId); } } render() { const { projectInfo } = this.state; return {projectInfo.name} {projectInfo.detail} }}復制代碼

14.ref

ref用來給元素或子組件注冊引用信息,允許我們訪問子組件或者子節(jié)點。

ref常用于:

  • 管理焦點,文本選擇或媒體播放。
  • 觸發(fā)強制動畫。

vue

通過給組件或者子元素設(shè)置ref這個attribute為子組件或者子元素賦予一個ID引用。

$refs只會在組件渲染完成之后生效,并且它們不是響應式的。這僅作為一個用于直接操作子組件的“逃生艙”——你應該避免在模板或計算屬性中訪問$refs。

(1)子元素引用ref

子元素上引用ref

加載完畢后使輸入框自動獲取焦點

mounted() { this.$refs.inputMessage.focus();}復制代碼

(2)子組件引用ref

子組件引用ref常用于父組件使用子組件的方法。

常用表單驗證就是采用這種方式驗證的。

提交復制代碼

react

react中不像vue中直接給ref傳字符串類型值,class組件通過React.createRef綁定ref屬性(React v16.0版本之后),函數(shù)組件通過useRef綁定ref屬性,還可以使用React.forwardRef用于轉(zhuǎn)發(fā)ref屬性到子組件中。

(1)class組件綁定ref

通過React.createRef在構(gòu)造函數(shù)中生成ref,在綁定到input元素上,加載完成后自動聚焦。

class NewComponent extends React.Component { constructor(props) { super(props); this.state = { message: 'hello world' }; this.inputRef = React.createRef(); } componentDidMount() { this.inputRef.current.focus(); } render() { const { message } = this.state; return ( {message} ); }}復制代碼

(2)函數(shù)組件綁定ref

函數(shù)組件可以使用useRef綁定ref屬性。useRef返回一個可變的ref對象,其 .current屬性被初始化為傳入的參數(shù)(initialValue)。返回的ref 對象在組件的整個生命周期內(nèi)保持不變。

function NewComponent() { const [message, setMessage] = useState('hello world.'); const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); }, []); return ( {message} );}復制代碼

(3)React.forwardRef 轉(zhuǎn)發(fā) ref 到子組件

React.forwardRef會創(chuàng)建一個React組件,這個組件能夠?qū)⑵浣邮艿膔ef屬性轉(zhuǎn)發(fā)到其組件樹下的另一個組件中。

這種技術(shù)并不常見,但在以下兩種場景中特別有用:

  • 轉(zhuǎn)發(fā)refs到DOM組件
  • 在高階組件中轉(zhuǎn)發(fā)refs

父組件直接傳遞ref屬性給子組件NewComponent。

function Parent() { const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); }, []); return

This is refs.

;}復制代碼

子組件使用React.forwardRef 接受渲染函數(shù)作為參數(shù),父組件加載完成后聚焦到input輸入框。

const NewComponent = React.forwardRef((props, ref) => ( {props.children}));復制代碼

15.表單(v-model vs value)

對于表單,vue中使用v-model在表單組件上實現(xiàn)雙向數(shù)據(jù)綁定,react中通過在表單組件上綁定value屬性以受控組件的形式管理表單數(shù)據(jù)。

vue

v-model指令在表單、及元素上創(chuàng)建雙向數(shù)據(jù)綁定。它會根據(jù)控件類型自動選取正確的方法來更新元素。v-model本質(zhì)上不過是語法糖。

v-model在內(nèi)部為不同的輸入元素使用不同的屬性并拋出不同的事件:

  • text和textarea元素使用value屬性和input事件;
  • checkbox和radio使用checked屬性和change事件;
  • select字段將value作為prop并將change作為事件。

(1)基本用法

Ⅰ.文本

input輸入框上綁定v-model屬性綁定msg,當修改input輸入值時,msg會自動同步為用戶輸入值。

v-model寫法等價于:value和@input的結(jié)合,:value綁定輸入值,@input表示接收輸入事件修改msg的值為輸入的值,從而實現(xiàn)雙向綁定。

(msg = e.target.value)" />復制代碼

Ⅱ.復選框

單個復選框綁定到布爾值

{{ checked }}復制代碼

多個復選框綁定到數(shù)組

apple banana mango Selected fruits: {{ selectedFruits }} 復制代碼

data

data() { return { selectedFruits: [] }; }復制代碼

Ⅲ.選擇框

1)選擇框單選時,綁定字符串

{{ option.text }} Selected: {{ selected }}復制代碼

data

data() { return { selected: "A", options: [ { text: "One", value: "A" }, { text: "Two", value: "B" }, { text: "Three", value: "C" } ] };}復制代碼

2)選擇框多選時,綁定的是數(shù)組

{{ option.text }} Selected: {{ selected }}復制代碼

data

data() { return { selected: ["A"], //多選時綁定的是數(shù)組 options: [ { text: "One", value: "A" }, { text: "Two", value: "B" }, { text: "Three", value: "C" } ] };}復制代碼

####(2)修飾符 vue對于v-model擴展了.lazy、.number、.trim修飾符增強功能。

Ⅰ.lazy

在默認情況下,v-model在每次input事件觸發(fā)后將輸入框的值與數(shù)據(jù)進行同步。添加了.lazy修飾符,轉(zhuǎn)變?yōu)閏hange事件進行同步。

復制代碼

Ⅱ.number

.number修飾符可以自動將用戶的輸入轉(zhuǎn)換為數(shù)值類型,尤其是處理數(shù)字類型表單項時尤其有用。

復制代碼

Ⅲ.trim

.trim修飾符可以自動過濾用戶輸入的首尾空白字符。

復制代碼

(3)自定義組件使用v-model

一個組件上的v-model默認會利用名為value的prop和名為 input的事件。

InputMessage綁定v-model值為msg

復制代碼

InputMessage組件通過value props接收值,emit input事件給父組件,修改父組件中msg的值。

復制代碼

react

react中,表單元素()通常維護自己的state,將state賦值給value屬性,并根據(jù)用戶輸入通過setState()更新state,以這種方式控制的表單元素稱為“受控組件”。

(1)受控組件

受控組件中,state作為組件“唯一的數(shù)據(jù)源”,組件還控制著用戶操作過程中表單發(fā)生的操作。

class CreateForm extends React.Component { constructor(props) { super(props); this.state = { name: '' } } nameChange = (event) => { // 接收事件作為參數(shù) this.setState({ name: event.target.value }); } render() { const { name } = this.state; return ( name: {name} ) }}復制代碼

(2)非受控組件

在react中,對于不能使用state方式管理的表單組件稱為非受控組件,非受控組件的值不能通過代碼控制,表單數(shù)據(jù)交由DOM節(jié)點來處理。對于非受控組件,可以使用ref從DOM節(jié)點中獲取表單數(shù)據(jù)。

始終是一個非受控組件,通過創(chuàng)建ref的形式獲取文件數(shù)據(jù)。

class CreateForm extends React.Component { constructor(props) { super(props); this.fileRef = React.createRef(null); } fileChange = (event) => { event.preventDefault(); const file = this.fileRef.current.files[0]; console.log(file) } render() { return (

16.插槽(slot vs Render Props+this.props.children)

vue和react中都實現(xiàn)了“插槽”(內(nèi)容分發(fā))功能,vue中主要通過slot實現(xiàn)插槽功能,react中通過this.props.children和Render props實現(xiàn)類似vue中的插槽功能。

vue

vue中通過實現(xiàn)插槽功能,包含默認插槽、具名插槽、作用域插槽。

(1)默認插槽

默認插槽使用在組件內(nèi)預留分發(fā)內(nèi)容的“占位”,在組件起始標簽和結(jié)束標簽可以包含任何代碼,例如html或者其他組件。

關(guān)于默認插槽,有2點說明:

(1)如果不使用插槽,插入到組件中的內(nèi)容不會渲染。 (2)插槽可以設(shè)置后備內(nèi)容,在不插入任何內(nèi)容時顯示。

使用默認插槽的組件:

Slot:

Default content. // 使用slot預留插槽占位,slot中的內(nèi)容作為后備內(nèi)容 復制代碼

父組件使用該組件,在組件起始標簽和結(jié)束標簽添加插槽內(nèi)容。

This is slot component.

復制代碼

最終插槽內(nèi)容會被插入到組件占位的位置。

Slot:

This is slot component.

復制代碼

當沒有添加插槽內(nèi)容時,會渲染默認插槽內(nèi)容。

Slot:

Default content. 復制代碼

(2)具名插槽

默認插槽只能插入一個插槽,當插入多個插槽時需要使用具名插槽。slot元素有一個默認的attribute name,用來定義具名插槽。

默認插槽的name是default。

在向具名插槽提供內(nèi)容的時候,我們可以在一個 元素上使用v-slot指令,并以v-slot的參數(shù)的形式提供其名稱,將內(nèi)容插入到對應的插槽下。

v-slot:也可以簡寫為#,例如v-slot:footer可以被重寫為#footer。

插槽組件slot-component有header footer兩個具名插槽和一個默認插槽。

Header content. Main content. Footer content. 復制代碼

向插槽中分別插入內(nèi)容:

This is header content. This is main content. This is footer content. 復制代碼

最終html會被渲染為:

This is header content. This is main content. This is footer content. 復制代碼

(3)作用域插槽

有時候我們需要在父組件中顯示插槽組件的數(shù)據(jù)內(nèi)容,這時候作用域插槽就派上用場了。

作用域插槽需要在元素上綁定attribute,這被稱為插槽prop。在父級作用域中,可以使用帶值的v-slot來定義我們提供的插槽prop的名字。

插槽組件

Header content. {{ person.name }} 復制代碼

父組件作用域?qū)胁宀踦rop的對象命名為slotProps,也可以使用任意你喜歡的名字。

This is header content. // 使用帶值的`v-slot`來定義插槽`prop`的名字 {{ slotProps.person.name }} {{ slotProps.person.age }} 復制代碼

最終html將被渲染為:

This is header content. xiaoming 14 復制代碼

react

react中通過this.props.children和Render props實現(xiàn)類似vue中的插槽功能。

(1)this.props.children

每個組件都可以通過this.props.children獲取包含組件開始標簽和結(jié)束標簽之間的內(nèi)容,這個與vue中的默認插槽類似。

在class組件中使用this.props.children,在function組件中使用props.children。 class組件使用this.props.children獲取子元素內(nèi)容。

class NewComponent extends React.Component { constructor(props) { super(props); } render() { return {this.props.children} }}復制代碼

function組件使用props.children獲取子元素內(nèi)容。

function NewComponent(props) { return >{props.children}}復制代碼

父組件使用NewComponent組件

This is new component header.

This is new component content. 復制代碼

最終html將被渲染為:

This is new component header.

This is new component content.復制代碼

(2)Render props

render prop是指一種在React組件之間使用一個值為函數(shù)的prop共享代碼的技術(shù)。render prop是一個用于告知組件需要渲染什么內(nèi)容的函數(shù)prop。

比如我們常用的react-router-dom中的Route的component prop就采用了典型的render prop的用法。

// component props接收具體的組件 復制代碼

通過多個render prop即可實現(xiàn)類似vue中具名插槽的功能。

NewComponent定義了header、main、footer prop。

class NewComponent extends React.Component { constructor(props) { super(props); } render() { const { header, main, footer, children } = this.props; return ( {header || (Header content.)} {main || (Main content.)} {children} {footer || (Footer content.)} ); }}復制代碼

父組件向子組件傳遞render prop。

This is header content. } content={

總結(jié)

以上是生活随笔為你收集整理的react map循环生成的button_关于Vue和React的一些对比及个人思考(中)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。