从实用性角度出发,暂时不学习class创建组件的方式了。
直接入手function 创建组件。
prop的一些使用
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
| // 一个props对象,从里面拿组件参数
export function ACard(props:{title:string}){
return (
<div className="card">
{props.title}
</div>
)
}
// 解构
export function ACard({title}:{title:string}){
return (
<div className="card">
{title}
</div>
)
}
// 默认值
export function ACard({title='title'}:{title:string}){
return (
<div className="card">
{title}
</div>
)
}
// 父组件传递给子组件
export function Test({title}:{title:string}){
return (
<>
<div>{title}</div>
</>
)
}
export function BCard({props}:{props:{title:string}}){
return (
<>
<Test {...props}></Test>
</>
)
}
// 传递jsx片段
export function Test({content}:{content:React.ReactNode}){
return (
<>
<div>{content}</div>
</>
)
}
export function CCard(){
const content = <div>123</div>
return (
<>
<Test content={content} />
</>
)
}
|
条件渲染
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| export function ListItem({ title, isPacked }: { title: string, isPacked: boolean }) {
if (isPacked) {
return <li>packed</li>
}
else {
return <li>{title}</li>
}
}
export function conditionRender() {
return (
<>
<ul>
<ListItem isPacked={true} title="hello"></ListItem>
<ListItem isPacked={false} title="hello"></ListItem>
</ul>
</>
)
}
|
返回null = 不渲染
1
2
3
| if (isPacked) {
return null
}
|
三元表达式条件渲染
1
2
3
| export function ListItem({ title, isPacked }: { title: string, isPacked: boolean }) {
return <li>{isPacked ? title : ''}</li>
}
|
与(&&) 运算符
1
2
3
| export function ListItem({ title, isPacked }: { title: string, isPacked: boolean }) {
return <li>{isPacked && title}</li>
}
|
列表渲染
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| const people = [
'Creola Katherine Johnson: mathematician',
'Mario José Molina-Pasquel Henríquez: chemist',
'Mohammad Abdus Salam: physicist',
'Percy Lavon Julian: chemist',
'Subrahmanyan Chandrasekhar: astrophysicist',
]
export function ListRender() {
const listItems = people.map(person =>
<li>{person}</li>,
)
return <ul>{listItems}</ul>
}
|