温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在React中设置 styled-components组件属性

发布时间:2021-05-25 17:39:55 来源:亿速云 阅读:179 作者:Leah 栏目:web开发

这篇文章给大家介绍怎么在React中设置 styled-components组件属性,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

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中设置 styled-components组件属性 

打开react developer tools查看

怎么在React中设置 styled-components组件属性 

这时可以发现其实并不是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;
  }
`;

关于怎么在React中设置 styled-components组件属性就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI