当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React styled-components设置组件属性的方法

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

2019年06月04日  | 移动技术网IT编程  | 我要评论

问题

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网