styled-components設置組件屬性

問題

最近在試着用react做一個音樂播放器,在這之前其實並不瞭解styled-components,但由於使用css in js並且想實現hover效果,百度各種解決方案後發現了styled-components這個好東西,如果你看到了這篇博客,就證明你應該瞭解或者熟練運用styled-components了。
回到項目開發中,一個音樂播放器應該由多個組件組成,其中有一個list組件用於展示歌曲列表,就像這樣
這裏寫圖片描述
鵝。。。好像暴露了我的喜好。。。
每一列就是一個div(當然ul也是可以的),爲了方便後續功能的實現,我把每首歌的海報、音頻文件的地址當做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;

代碼很簡單,但最後我們會發現這樣一個問題——在頁面中生成的div元素只有poster屬性而沒有audio屬性
這裏寫圖片描述
打開react developer tools查看
這裏寫圖片描述
這時可以發現其實並不是styled.div直接編譯成原生html元素,而是會生成一個div(當然,如果是styled.button就會額外生成一個子button),最後在頁面中顯示的就是這個div
也可以發現在styled.div中兩個屬性都是設置好的,但在子div中就只有一個屬性了,通過反覆嘗試可以發現,直接在styled-components組件中設置屬性,除了className之外就只有一個屬性會生效

解決

解決的辦法就是多看幾遍styled-components文檔,我們就會發現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屬性都有。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章