React框架基础

基本语法

常量或函数定义方式:const 函数或常量名 =

函数定义方式:const xxx = (传入参数) => {代码部分}

函数中内容写法:表达式都需要添加大括号

三元表达式:值? 选择1:选择2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const name = '1234567'
const getage = () => {
return 'fdd'
}
const flag = true
function App() {
return (
<div className="App"> //div 中可以设置class和id等
{name}
{getage()}
{flag? 'kkk':'jjj'}
</div>
);
}

定义一个列表:与python中类似。在调用时需要用到.map函数,同时需要指定一个名字来接住map遍历出的每一个元素。格式可见下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const singer_list = [
{id: 1, name:"jay"},
{id: 2, name:"mayday"},
{id: 3, name:"joker"},
{id: 4, name:"jolin"}
]
function App() {
return (
<div className="App">
<ul>
{singer_list.map(singer=> <li key={singer.id}>{singer.name}</li>)}
</ul>
</div>
);
}

调用写好的函数:见下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const gettag = (type)=>{
if (type === 1){
return <h1>this is h1</h1>
}
if (type === 2){
return <h2>this is h2</h2>
}
if (type === 3){
return <h3>this is h3</h3>
}
}
function App() {
return (
<div className="App">
{gettag(1)}
</div>
);
}

行内样式:直接在元素上绑定style。注意这里的style里面需要两个大括号

1
2
3
4
5
6
7
function App() {
return (
<div className="App">
<span style={{color:'red', fontSize:'30px'}}>this is span</span>
</div>
);
}

或者

1
2
3
4
5
6
7
8
9
10
11
12
const style1 = {
color:'red',
fontSize:'30px'
}

function App() {
return (
<div className="App">
<span style={style1}>this is span</span>
</div>
);
}

类名样式:在元素身上绑定class name。用类来进行样式控制,在写类的时候用.开头,如下

1
2
3
4
//文件名:App.css
.active{
color: red;
}

下面在App.js中进行调用

1
2
3
4
5
6
7
8
9
import './App.css'

function App() {
return (
<div className="App">
<span className='active'>this is span</span>
</div>
);
}

动态类名控制:也即有时候需要使用这种类型,有时候是另一种类型。

1
2
3
4
5
6
7
8
const flag = false
function App() {
return (
<div className="App">
<span className={flag? 'active': 'inactive'}>this is span</span>
</div>
);
}
Author: YihangBao
Link: https://roarboil.github.io/2022/06/26/react-base/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.