如何将这段CSS代码转换为Styled-Components?
转换为Styled-Components的写法
首先确保你已经安装了styled-components(未安装的话执行 npm install styled-components 或 yarn add styled-components),之后按以下方式改写代码:
基础写法
import styled from 'styled-components'; // 创建搜索容器的styled组件 const StyledSearchBox = styled.div` // 修正原CSS的错误属性:box-radius → border-radius border-radius: 40px; // 实现父元素hover时子input的样式变化 &:hover > input { padding: 10px; } `; const Page = () => { return( <StyledSearchBox> <input /> </StyledSearchBox> ) } export default Page;
拆分input为独立styled组件的写法
如果需要给input单独定义基础样式,可以拆分出独立的styled组件:
import styled from 'styled-components'; const StyledSearchBox = styled.div` border-radius: 40px; // 通过组件引用实现hover关联样式 &:hover > ${TextInput} { padding: 10px; } `; const TextInput = styled.input` // 这里可以添加input的基础样式,比如: // border: none; // outline: none; `; const Page = () => { return( <StyledSearchBox> <TextInput /> </StyledSearchBox> ) } export default Page;
关键说明
- styled-components使用模板字符串编写CSS,完全兼容原生CSS语法
- 父元素的hover状态通过
&:hover表示,嵌套选择器直接写在对应组件的样式块中 - 原CSS中的
box-radius是无效属性,已修正为标准的border-radius
内容的提问来源于stack exchange,提问作者Omphile James
相关产品推荐
相关产品推荐

