文章目录
1.jsx标签
jsx标签与html标签区别:
-
首字母大小写
- 大写是自定义组件
- 小写为html标签
-
标签必须闭合
- jsx标签必须闭合
-
每段jsx只能有一个根结点
-
错误示例
const com = ( <h1>hell</h1> <p>world</p> )
-
基于该要求,可能有很多无意义的标签,此时可以使用fragment标签作为根标签,缩写如下:
<> </>
-
2.jsx属性
html中与jsx/tsx中关键字有冲突的修改名字。
-
class改为className,因为class为jsx/tsx的关键字
<div className="card"> ... </div>
-
style要使用js对象(不能是string)而且key用驼峰写法
<h1 style={{ color: "red", backgroundColor: "white" }}>Vite + React</h1>
-
for改为htmlFor
<div> <label htmlFor="name">姓名:</label> <input id="name" type="text" /> </div>
效果如下图所示:
3.jsx 事件
- 使用onXxx的形式
- 必须传入一个函数(是fn而非fn())
- 注意typescript类型
3.1 声明事件
const fn = () => {
console.log("clicked");
};
...
<div>
<button type="button" onClick={fn}>
点击
</button>
</div>
3.2 使用事件(对象)
import type { MouseEvent } from "react";
const fn = (e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault(); // 阻止默认行为
e.stopPropagation; // 阻止冒泡
console.log("clicked");
};
4. typescript类型基础
4.1 类型声明
-
变量声明
const n: number = 100;
-
函数参数
function fn(a: number, b: number) { return a + b; } fn(10, 20);
4.2 事件函数传递自定义参数
const fn = (e: MouseEvent<HTMLButtonElement>, name: string): void => {
e.preventDefault(); // 阻止默认行为
e.stopPropagation; // 阻止冒泡
console.log("clicked");
console.log("name: " + name);
};
<div>
<button
type="button"
onClick={(e) => {
fn(e, "button");
}}
>
点击
</button>
</div>
5.插入js变量
-
使用{xxx} 可以插入js变量、函数、表达式
<img src={viteLogo} className="logo" alt="Vite logo" /> <button type="button" onClick={(e) => { fn(e, "button"); }} > 点击 </button> {/* <p>{viteLogo}</p> */}
-
可以插入普通文件、属性
-
可用于注释
6. 条件判断
-
&&逻辑符号
const flag = true; <div>{flag && <p>hello</p>}</div>
-
三元表达式
const flag = true; <div>{flag ? <p>hello</p> : <p>你好</p>}</div>
-
函数
const flag = true; function hello() { return flag ? <p>hello</p> : <p>你好</p>; } <Hello /> {/*{标签,首字母大写,自定义标签}*/}
7. 循环
-
使用使用数组map
-
每个item元素需要key属性
-
key在同级别唯一,强烈不建议使用index作为key
const list = [ { name: "张三", age: 18 }, { name: "李四", age: 22 }, { name: "王五", age: 23 }, { name: "六子", age: 54 }, ]; <ul> {list.map((user) => { const { name, age } = user; return <li key={name}>{age}</li>; })} </ul>
结语
❓QQ:806797785
⭐️仓库地址:https://gitee.com/gaogzhen
⭐️仓库地址:https://github.com/gaogzhen
[1]Introducing JSX[CP/OL].
[2]typescript[CP/OL].