React与styled-components:如何向ButtonStyle传递图标Props?
解决方法
你的代码存在几个关键问题,导致图标无法正确传递到:before的content属性,以下是修正方案:
1. 修正CSS content 的赋值方式
CSS的content属性要求值为字符串(需用引号包裹),你之前的写法没有添加引号,导致CSS解析错误。同时,无图标时要返回空字符串而非'empty',避免显示多余文本:
&:before { content: ${props => props.icon ? `'${props.icon}'` : `''`}; }
2. 补充icon的PropTypes定义
你的Button组件接收icon属性,但未在propTypes中声明,补上后能提升代码规范性:
Button.propTypes = { // ... 原有属性 icon: PropTypes.string };
3. 修复样式中的语法错误
ButtonStyle里的color ##ddd缺少冒号,修正为:
color: #ddd;
完整修正后的代码
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; const ButtonStyle = styled.button` padding: 1em 1.5em; margin: 1em; background: white; border: 0; border-radius: 5px; color: #ddd; transition: background 0.4s; transition-timing-function: ease; cursor: pointer; text-align: center; text-transform: uppercase; &:active { color: #000; } &:hover { background: #CC3333; color: #fff; } &:before { content: ${props => props.icon ? `'${props.icon}'` : `''`}; } ` const FontsButtonStyle = styled(ButtonStyle)` @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap'); font-weight: 800; font-family: 'Bebas Neue', cursive; ` const Button = ({type, disabled, name, title, onClick, className, icon}) => ( <FontsButtonStyle icon={icon} type={type} disabled={disabled} name={name} onClick={onClick} className={className}> {title} </FontsButtonStyle> ); Button.propTypes = { disabled:PropTypes.bool, type:PropTypes.string, name:PropTypes.string, title:PropTypes.string, onClick:PropTypes.func, className:PropTypes.string, icon: PropTypes.string }; Button.defaultProps = { disabled: false, type: 'button', name: 'Press me!', title: 'Press me!', onClick: () => { alert('onClick Works!') }, className:'', icon: '😂' }; export default Button;
内容的提问来源于stack exchange,提问作者Rolowy
相关产品推荐
相关产品推荐

