React styled-components設(shè)置組件屬性的方法
問題
最近在試著用react做一個音樂播放器,在這之前其實并不了解styled-components,但由于使用css in js并且想實現(xiàn)hover效果,百度各種解決方案后發(fā)現(xiàn)了styled-components這個好東西,如果你看到了這篇博客,就證明你應(yīng)該了解或者熟練運用styled-components了。
回到項目開發(fā)中,一個音樂播放器應(yīng)該由多個組件組成,其中有一個list組件用于展示歌曲列表,就像這樣
鵝。。。好像暴露了我的喜好。。。
每一列就是一個div(當然ul也是可以的),為了方便后續(xù)功能的實現(xiàn),我把每首歌的海報、音頻文件的地址當做div的屬性儲存起來。list組件的代碼如下
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;
代碼很簡單,但最后我們會發(fā)現(xiàn)這樣一個問題——在頁面中生成的div元素只有poster屬性而沒有audio屬性
打開react developer tools查看
這時可以發(fā)現(xiàn)其實并不是styled.div直接編譯成原生html元素,而是會生成一個div(當然,如果是styled.button就會額外生成一個子button),最后在頁面中顯示的就是這個div。
也可以發(fā)現(xiàn)在styled.div中兩個屬性都是設(shè)置好的,但在子div中就只有一個屬性了,通過反復(fù)嘗試可以發(fā)現(xiàn),直接在styled-components組件中設(shè)置屬性,除了className之外就只有一個屬性會生效
解決
解決的辦法就是多看幾遍styled-components文檔,我們就會發(fā)現(xiàn)styled-components有一個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;
}
`;
props對象就是我們傳入ContentDiv的屬性,這樣一來,最后生成的div中poster與audio屬性都有。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React Hook父組件如何獲取子組件的數(shù)據(jù)/函數(shù)
這篇文章主要介紹了React Hook父組件如何獲取子組件的數(shù)據(jù)/函數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
Taro?React自定義TabBar使用useContext解決底部選中異常
這篇文章主要為大家介紹了Taro?React底部自定義TabBar使用React?useContext解決底部選中異常(需要點兩次才能選中的問題)示例詳解,有需要的朋友可以借鑒參考下2023-08-08
React中的stopPropagation和preventDefault實踐記錄
本文詳細介紹了事件冒泡、捕獲與React合成事件體系下的表現(xiàn)區(qū)別,包括事件傳播階段、處理方式、事件池機制等核心概念,對React?stopPropagation和preventDefault相關(guān)知識感興趣的朋友跟隨小編一起看看吧2025-11-11
React中使用ResizeObserver來觀察元素size變化的方法
在 React 中使用 ResizeObserver 來觀察元素的大小變化,可以通過創(chuàng)建一個自定義 Hook 來封裝 ResizeObserver 的邏輯,并在組件中使用這個 Hook,以下是一個完整的示例,展示了如何在 React 中使用 ResizeObserver 來觀察元素的大小變化,需要的朋友可以參考下2024-12-12

