2.修改css样式

7/18/2023 react

# 1.结合 styled-components 修改 antd 组件CSS样式

// 首先需要安装
yarn add styled-components

// 首先新建一个tsx文件存放样式 NavTabs.styled.tsx
// NavTabs: 注意是大写
// 设置tabs内容不显示
export const NavTabs = styled.div`
  padding: 0 16px;

  .ant-tabs {  
    .ant-tabs-content-holder {
      display: none;
    }
  }
`;

// Nav.tsx
// NavTabs作为标签使用
import { NavTabs } from "./NavTabs.styled.tsx";
<NavTabs>
   <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
</NavTabs>
// 使用style-components会随机生成一个哈希字符串,这样不会污染到全局变量,当然因为随机生成,维护会增加难度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 2.在组件中引入 [name].module.scss 文件

// 首先创建对应文件的scss文件 Register.module.scss
.container {
  height: calc(100vh - 64px - 65px);
  display: flex;
  justify-content: center;
  align-items: center;a
  flex-direction: column;
  background-color: #fff;
 .content {
	  box-shadow: 0 4px 10px gray;
	  padding: 32px 52px;
	  border-radius: 8px;
 }
}

// 对应注册文件:Register.tsx
import styles from './Register.module.scss'
<div className={styles.container}>
  <div className={styles.content}>
	  注册内容xxx
	</div>
</div>

// xx.scss可能会造成样式污染,
// xx.module.scss,可以在不同的文件中使用相同的 CSS 类名(隔离样式),而不必担心命名冲突。生成的唯一类名是基于哈希值的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 3.修改本页面的样式。行内样式修改

<OriginalMenu style={{ display: (showDiffMenu === 'system') ? 'block' : 'none'}}>
<Button style={{ backgroundColor: "transparent", padding: 0 }}>按钮</Button>

// 或者
class Header extends Component {
  render(){
    const btnStyle = {
      width: '100px',
      height: '40px',
      borderRadius: '3px',
      outline: 'none',
      border: 'none',
      cursor: 'pointer',
      background: '#abcdef',
      color: '#fff'
    }
    return (
      <Fragment>
        <button style = { btnStyle }>button按钮</button>
      </Fragment>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

注意:

// 注意:css没有本地作用域,所有声明的样式都是全局的(global styles)。页面上任意元素只要匹配上某个选择器的规则,这个规则就会被应用上,而且规则和规则之间可以叠加作用

// Test1.css
.testDiv {
  width: 100px;
  height: 100px;
  background-color: blueviolet;
}

// Test1.tsx
import '@/Test1.css'
const Test1: React.FC = () => {
  return (
    <>
      <div className="testDiv">test1</div>
    </>
  )
}
export default Test1


// Test2.tsx
const Test2: React.FC = () => {
  return (
    <>
      <div className="testDiv">test2</div>
    </>
  )
}
export default Test2
// 此时,Test2.tsx文件没有引入css文件,只是写了相同的类名'testDiv',此类名与css文件中的类名相同,css没有作用域,该样式就会被应用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
最近更新时间: 7/24/2023, 6:22:59 AM
강남역 4번 출구
Plastic / Fallin` Dild