ReactJS中如何修改传入组件的样式?使用styled-components遇阻
解决styled-components样式传入组件的问题
嘿,我懂你现在的困惑啦!你这里踩了一个styled-components新手很容易犯的坑——把styled-components生成的组件当成普通的style属性值来传递了,这肯定没法生效的~
问题根源
styled.button返回的是一个完整的React组件,而组件的style属性接受的是CSS样式对象(比如style={{ padding: '10px' }}),这俩完全不是一回事儿,所以你的写法才会出问题。
正确的修改方法
根据你的ButtonOne是用styled-components定义的情况,给你两种最常用的解决方案:
方案1:继承ButtonOne的样式(推荐)
既然ButtonOne本身就是styled-components组件,你可以直接让新的样式组件继承它的基础样式,再添加额外样式:
// 先导入你的ButtonOne组件 import ButtonOne from './ButtonOne'; // 继承ButtonOne的样式,添加新的规则 const SearchBarContainer_Button = styled(ButtonOne)` padding: 10px; margin-left: 10px; width: 300px; `; // 使用的时候直接渲染这个新组件 <SearchBarContainer_Button type="submit" className="search-bar__button"> {this.props.buttonText || 'search'} </SearchBarContainer_Button>
这种方式完美保留了styled-components的特性(比如样式隔离、动态样式支持),是最规范的写法。
方案2:直接传递style对象(不推荐,但适合临时场景)
如果你只是想快速给ButtonOne加一些行内样式,可以把样式写成对象传给style属性,而不是用styled-components:
<ButtonOne style={{ padding: '10px', marginLeft: '10px', width: '300px' }} type="submit" className="search-bar__button" > {this.props.buttonText || 'search'} </ButtonOne>
不过这种方式没法利用styled-components的优势,只适合简单的临时样式。
额外提醒
以后记住:styled-components创建的是组件,不是样式对象,你需要直接把它当成React组件来渲染,而不是作为属性传给其他组件哦~
内容的提问来源于stack exchange,提问作者Essi Joon
相关产品推荐
相关产品推荐

