您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在React中設(shè)置 styled-components組件屬性,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
import React from 'react'; import styled from 'styled-components'; // 設(shè)置樣式 const ContentDiv = styled.div` display: flex; justify-content: space-between; height: 50px; line-height: 50px; transition: 0.5s; cursor: pointer; &:hover{ color: #31c27c; } `; const LengthDiv = styled.div` color: #999; `; // list組件 class List extends React.Component { constructor(props){ super(props); this.state = { // 播放列表 list: this.props.list }; } render(){ const listItem = this.state.list.map((item, index) => { return ( <ContentDiv key={ item.name } poster={ item.poster } audio={ item.music }> <div> { item.name } - { item.author } </div> <LengthDiv> { item.length } </LengthDiv> </ContentDiv> ); }); return ( <div> { listItem } </div> ) } } export default List;
代碼很簡單,但最后我們會(huì)發(fā)現(xiàn)這樣一個(gè)問題——在頁面中生成的div元素只有poster屬性而沒有audio屬性
打開react developer tools查看
這時(shí)可以發(fā)現(xiàn)其實(shí)并不是styled.div直接編譯成原生html元素,而是會(huì)生成一個(gè)div(當(dāng)然,如果是styled.button就會(huì)額外生成一個(gè)子button),最后在頁面中顯示的就是這個(gè)div。
也可以發(fā)現(xiàn)在styled.div中兩個(gè)屬性都是設(shè)置好的,但在子div中就只有一個(gè)屬性了,通過反復(fù)嘗試可以發(fā)現(xiàn),直接在styled-components組件中設(shè)置屬性,除了className之外就只有一個(gè)屬性會(huì)生效
解決
解決的辦法就是多看幾遍styled-components文檔,我們就會(huì)發(fā)現(xiàn)styled-components有一個(gè)attr方法來支持為組件傳入 html 元素的其他屬性,那么原來的list組件就只需要修改ContentDiv變量即可
const ContentDiv = styled.div.attrs({ poster: props => props.poster, audio: props => props.audio })` display: flex; justify-content: space-between; height: 50px; line-height: 50px; transition: 0.5s; cursor: pointer; &:hover{ color: #31c27c; } `;
關(guān)于怎么在React中設(shè)置 styled-components組件屬性就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。