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

时间:2021-05-26

问题

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

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章