react样式

1.内嵌样式

<div style={{color:"#ccc"}}>item</div>

2.选择器样式

<h3 className="title">Search Github Users</h3>

3.三目表达式

<span className={true ? 'span' : '' }>样式</span>

 4.样式模块化

第一步:css文件名称以:'名称.module.css'命名

第二步:在页面中导入使用,自定义模块化命名

比如:写的是头部的样式:import header from "./index.module.css"

第三步:使用时必须时---》模块化名称.选择器名称

 <h3 className={header.title}>样式</h3>

React官方并没有提供样式隔离的方案,但是我们可以采用自定义命名规范或使用第三方库来进行样式隔离。以下是两种常见的样式隔离方案: 1. 自定义命名规范 在React中,我们可以通过自定义命名规范来实现样式隔离。例如,在组件的class名称中添加特定的前缀,以确保这些样式只适用于当前组件。例如: ```jsx import React from 'react'; import './MyComponent.css'; const MyComponent = () => { return ( <div className="my-component"> <h1 className="my-component__title">Hello World</h1> <p className="my-component__text">This is my component</p> </div> ); }; export default MyComponent; ``` 在上面的例子中,我们在class名称中添加了my-component和my-component__title前缀,以确保这些样式只适用于当前组件。 2. 使用第三方库 另一种常见的样式隔离方案是使用第三方库,例如css-in-js库。其中,emotion是一个流行的css-in-js库,它可以让我们在React组件中使用CSS。以下是使用emotion实现样式隔离的示例: 首先,安装emotion: ```shell npm install @emotion/react ``` 然后,在组件中使用emotion: ```jsx import React from 'react'; import { css } from '@emotion/react'; const MyComponent = () => { const myComponentStyles = css` background-color: #f0f0f0; padding: 20px; `; const titleStyles = css` font-size: 24px; color: #333; `; const textStyles = css` font-size: 16px; color: #666; `; return ( <div css={myComponentStyles}> <h1 css={titleStyles}>Hello World</h1> <p css={textStyles}>This is my component</p> </div> ); }; export default MyComponent; ``` 在上面的例子中,我们使用了css函数来定义组件的样式,并将其传递给组件的css属性。这样,我们就可以在组件中使用CSS,并确保这些样式只适用于当前组件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值