React組件對子組件children進(jìn)行加強的方法
問題
如何對組件的children進(jìn)行加強,如:添加屬性、綁定事件,而不是使用<div>{this.props.children}</div>在<div>上進(jìn)行處理。
前車之鑒
今天寫組件遇到這個問題,在網(wǎng)上查閱了很多資料,都說可以使用React.cloneElement進(jìn)行處理,但是結(jié)果并不是預(yù)期想要的。
先看看這個東西有什么用:
React.cloneElement(element, [props], [...childrn])
根據(jù)React官網(wǎng)的說法,以上代碼等價于:
<element.type {...element.props} {...props}>{children}</element.type>
這么做其實也是給children包了一層標(biāo)簽,再對其進(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' } } )
但是實際效果是這樣的:
<div style={{ dispaly: 'inline-block' }}> <div style={{ color: 'red' }} onClick={() => console.log('hello')}> demo </div> <div>
哈?。孔釉氐母冈乇辉O(shè)為了inline-block,和我們想要的<div>demo</div>被設(shè)為inline-block。結(jié)果與預(yù)期完全不同,簡直大失所望?。?!
React.clone根本對不起它clone的名字?。?!
自我探索
思路: jsx語法表示的元素只是react組件的一個語法糖。所以組件是對象。既然是對象我們就可以直接對其進(jìn)行修改。
嘗試在控制臺打印一個如下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é)
如何對組件的children進(jìn)行直接加強,直接修改this.props.children對象即可。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
解讀useState第二個參數(shù)的"第二個參數(shù)"
這篇文章主要介紹了useState第二個參數(shù)的"第二個參數(shù)",具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Can't?perform?a?React?state?update?on?an?unmoun
這篇文章主要為大家介紹了Can't?perform?a?React?state?update?on?an?unmounted?component報錯解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12