多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 为组件添加 class CSS 的 class 依赖组件的 props 或 state 的情况很常见 ```js render() { let className = 'menu'; if (this.props.isActive) { className += ' menu-active'; } return <span className={className}>Menu</span> } ``` 如果经常写上面的代码,也可以使用 [classnames](https://www.npmjs.com/package/classnames#usage-with-reactjs) 来简化我们的书写 # 固定样式和动态样式混合写法 情况 1:只写动态 class ```js <div className={index===this.state.currentIndex?"active":null}>此标签是否选</div> ``` 情况 2:既有本身 class 又要写动态 class ```js <div className={["container tab", index===this.state.currentIndex?"active":null].join(' ')}>此标签是否选中</div> ``` ES6 写法 ```js <div className={`container tab ${index === this.state.currentIndex ? "active" : null}`}>此标签是否选中</div> ``` # 行内样式 style 接受一个采用小驼峰命名属性的 JavaScript 对象,而不是 CSS 字符串。这与 DOM 中 style 的 JavaScript 属性是一致的,同时会更高效的,且能预防跨站脚本(XSS)的安全漏洞。例如: ```js const divStyle = { color: 'blue', backgroundImage: 'url(' + imgUrl + ')', }; function HelloWorldComponent() { return <div style={divStyle}>Hello World!</div>; } ``` React 会自动添加 ”px” 后缀到内联样式为数字的属性后。如需使用 ”px” 以外的单位,请将此值设为数字与所需单位组成的字符串。例如: ```html // Result style: '10px' <div style={{ height: 10 }}> Hello World! </div> // Result style: '10%' <div style={{ height: '10%' }}> Hello World! </div> ``` # styled-component [官方文档](https://www.styled-components.com/docs/basics) <span style="font-family: 黑体;font-size: 18px;font-weight: 500;">Installation</span> `npm install --save styled-components` <span style="font-family: 黑体;font-size: 18px;font-weight: 500;">Getting Started</span> ``` // Create a Title component that'll render an <h1> tag with some styles const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; // Create a Wrapper component that'll render a <section> tag with some styles const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // Use Title and Wrapper like any other React component – except they're styled! render( <Wrapper> <Title> Hello World! </Title> </Wrapper> ); ```