react致力于用js写所有html以及逻辑相关的代码部分,既然如此,何不用js写css控制组件样式呢? styled-components顺势而生
请一定要看到最后!!最后有小惊喜!
这个代码要有装一个插件才能高亮哦!
const componentsName=styled.tagname`[css写法]` 复制代码
//一个名为title的组件其会render一个style如模板字符串的h1 tag const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; const Wrapper = styled.section` padding: 4em; background: papayawhip; `; render( <Wrapper> <Title> Hello World! </Title> </Wrapper> ); 复制代码
const Button = styled.button` background: ${props => props.primary ? "palevioletred" : "white"}; color: ${props => props.primary ? "white" : "palevioletred"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; ` render( <div> <Button>Normal</Button> <Button primary>Primary</Button> </div> ) 复制代码
形如:
Const sub=styled(super)
const Button = styled.button` color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; ` const TomatoButton = styled(Button)` color: tomato; border-color: tomato; ` render( <div> <Button>Normal Button</Button> <TomatoButton>Tomato Button</TomatoButton> </div> ); 复制代码
const Component = styled.div` color: red; ` render( <Component as="button" onClick={() => alert('It works!')} > Hello World! </Component> ) 复制代码
const Link = ({ className, children }) => ( <a className={className}> {children} </a> ) const StyledLink = styled(Link)` color: palevioletred; font-weight: bold; ` 复制代码
const Thing = styled.div` &.blue{ color: blue; } .red { color: red; } const Thing2 = styled.div` /* 应用于紧邻Thing组件的下一个Thing组件 */ & + & { color: red; } ` render( <React.Fragment> <Thing2>第一个Thing组件</Thing2> <Thing2>第二个Thing组件</Thing2> <Thing className="blue" >Thing组件</Thing> <Thing> <p className="red" >p标签</p> </Thing> </React.Fragment> ) 复制代码
import React from 'react' import styled from 'styled-components' export default () => { return ( <Root> <div className="son1"> <div className="grandson1"> </div> </div> <div className="son2"> <div className="grandson2"> </div> </div> </Root> ) } const Root = styled.div` /* 把root的样式写这 */ .son1{ /* son1样式 */ .grandson1{ /* grandson1样式 */ } } .son2{ /* son2样式 */ .grandson2{ /* grandson2样式 */ } } ` 复制代码
拜托拜托!!🙏
点个赞再走吧!
点完👍快去用styled-components!
你一定会爱上的!!\
本文使用 mdnice 排版