React: Styled-Components

    技术2023-08-18  92

    https://styled-components.com/

    安装——npm install --save styled-components import——import styled from 'styled-components'

    Styled-Components

    可将css与js合并;

    import React from 'react'; // import './Person.css'; import styled from 'styled-components'; const person = (props)=>{ const Stylediv=styled.div` margin: 16px auto; color: rgb(73, 54, 47); width: 60%; border: 1px solid #eeeeee; box-shadow:0 2px 3px rgb(208, 214, 214); padding: 16px; text-align: center; @media (min-width:500px){ width:450px; } `; return( // <div className="Person" style={style}> <Stylediv> <p>I Am a person!</p> <p onClick = {props.click}>{props.name}</p> <p>i'm {props.age}</p> <p>{props.children}</p> <input type="text" onChange={props.changed} value={props.name}/> </Stylediv> ) }; export default person;

    将button和其style放入styled.button``中

    逗号变为分号; 大写变为-; hover等style前加&;

    import styled from 'styled-components'; //纯 css 写法 const StyleButton = styled.button` background-color:green; color:white; font:inherit; border:1px solid blue; padding:8px; cursor:pointer; &:hover{ background-color:lightgreen; color:black } `;

    调用改button

    <StyleButton onClick={this.clicktoshow}>Switch name </StyleButton>

    Styled-components设置动态css

    设置alt

    <StyleButton alt={this.state.isshow} onClick={this.clicktoshow}>Switch name </StyleButton>

    将button中得到props参数 根据传入的alt设定颜色;

    const StyleButton = styled.button` background-color:${props => props.alt? 'red':'green'}; color:white; font:inherit; border:1px solid blue; padding:8px; cursor:pointer; &:hover{ background-color:${props => props.alt? 'salmon':'lightgreen'}; color:black; } `;
    Processed: 0.009, SQL: 9