React styled-components設置組件屬性的方法
問題
最近在試著用react做一個音樂播放器,在這之前其實并不了解styled-components,但由于使用css in js并且想實現(xiàn)hover效果,百度各種解決方案后發(fā)現(xiàn)了styled-components這個好東西,如果你看到了這篇博客,就證明你應該了解或者熟練運用styled-components了。
回到項目開發(fā)中,一個音樂播放器應該由多個組件組成,其中有一個list組件用于展示歌曲列表,就像這樣
鵝。。。好像暴露了我的喜好。。。
每一列就是一個div(當然ul也是可以的),為了方便后續(xù)功能的實現(xiàn),我把每首歌的海報、音頻文件的地址當做div的屬性儲存起來。list組件的代碼如下
import React from 'react'; import styled from 'styled-components'; // 設置樣式 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中兩個屬性都是設置好的,但在子div中就只有一個屬性了,通過反復嘗試可以發(fā)現(xiàn),直接在styled-components組件中設置屬性,除了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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
React Draggable插件如何實現(xiàn)拖拽功能
這篇文章主要介紹了React Draggable插件如何實現(xiàn)拖拽功能問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07react-router-dom入門使用教程(前端路由原理)
這篇文章主要介紹了react-router-dom入門使用教程,主要包括react路由相關理解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08react拖拽react-beautiful-dnd一維數(shù)組二維數(shù)組拖拽功能
二維數(shù)組可以拖拽,但是不可以編輯+拖拽,如果想要實現(xiàn)編輯+拖拽,還是需要轉(zhuǎn)換成一維數(shù)組,本文給大家介紹react拖拽react-beautiful-dnd的相關知識,感興趣的朋友跟隨小編一起看看吧2024-03-03react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08