React styled-components设置组件属性的方法

2019-11-16,,

问题

最近在试着用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属性都有。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • React Component存在的几种形式详解
  • React 无状态组件(Stateless Component) 与高阶组件
  • React之PureComponent的使用作用
  • 详解在React.js中使用PureComponent的重要性和使用方式
  • 简谈创建React Component的几种方式

《React styled-components设置组件属性的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。