React組件對(duì)子組件children進(jìn)行加強(qiáng)的方法
問題
如何對(duì)組件的children進(jìn)行加強(qiáng),如:添加屬性、綁定事件,而不是使用<div>{this.props.children}</div>在<div>上進(jìn)行處理。
前車之鑒
今天寫組件遇到這個(gè)問題,在網(wǎng)上查閱了很多資料,都說可以使用React.cloneElement進(jìn)行處理,但是結(jié)果并不是預(yù)期想要的。
先看看這個(gè)東西有什么用:
React.cloneElement(element, [props], [...childrn])
根據(jù)React官網(wǎng)的說法,以上代碼等價(jià)于:
<element.type {...element.props} {...props}>{children}</element.type>
這么做其實(shí)也是給children包了一層標(biāo)簽,再對(duì)其進(jìn)行間接處理,沒有直接修改children。
如:
// App.jsx <Father> <div style={{ color: 'red' }} onClick={() => console.log('hello')}> demo </div> <Father>
我們希望在Father.jsx的內(nèi)部將div轉(zhuǎn)為inline-block。按照網(wǎng)上的做法,是這樣的:
// Father.jsx const Son = React.cloneElement( this.props.children, { style: { display: 'inline-block' } } )
但是實(shí)際效果是這樣的:
<div style={{ dispaly: 'inline-block' }}> <div style={{ color: 'red' }} onClick={() => console.log('hello')}> demo </div> <div>
哈???子元素的父元素被設(shè)為了inline-block,和我們想要的<div>demo</div>被設(shè)為inline-block。結(jié)果與預(yù)期完全不同,簡(jiǎn)直大失所望?。?!
React.clone根本對(duì)不起它c(diǎn)lone的名字!??!
自我探索
思路: jsx語(yǔ)法表示的元素只是react組件的一個(gè)語(yǔ)法糖。所以組件是對(duì)象。既然是對(duì)象我們就可以直接對(duì)其進(jìn)行修改。
嘗試在控制臺(tái)打印一個(gè)如下react組件:
// this.props.children console.log( <div style={{ color: 'red' }} onClick={() => { console.log('hello'); }} > demo </div> );
如下:
所以直接修改this.props.children即可:
// Father.jsx const { children } = this.props; const Son = { ...children, props: { ...children.props, dispaly: { ...children.style, display: 'inline-block' }, onTransitionEnd: () => { console.log('hello world') } } }
總結(jié)
如何對(duì)組件的children進(jìn)行直接加強(qiáng),直接修改this.props.children對(duì)象即可。
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
React實(shí)現(xiàn)評(píng)論的添加和刪除
這篇文章主要為大家詳細(xì)介紹了React實(shí)現(xiàn)評(píng)論的添加和刪除,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-10-10解讀useState第二個(gè)參數(shù)的"第二個(gè)參數(shù)"
這篇文章主要介紹了useState第二個(gè)參數(shù)的"第二個(gè)參數(shù)",具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Can't?perform?a?React?state?update?on?an?unmoun
這篇文章主要為大家介紹了Can't?perform?a?React?state?update?on?an?unmounted?component報(bào)錯(cuò)解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12react通過組件拆分實(shí)現(xiàn)購(gòu)物車界面詳解
這篇文章主要介紹了react通過組件拆分來(lái)實(shí)現(xiàn)購(gòu)物車頁(yè)面的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08