1.创建项目
// xxxxx 项目名称
pnpm create vite xxxxx --template=react-ts
2.函数式与Hooks已成为现代react开发的绝对标准 (用类开发代码臃肿)
import { useState } from 'react';
import './index.css';
//函数式开发
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1 onClick={() => setCount(count + 1)}>Hello React! {count}</h1>
</div>
);
}
export default App;
3.组件开发核心
1.组件输入的叫属性(props),组件内部的叫状态(State)
prop的使用(父子组件参数传递)
//子组件
import { useState } from "react";
//定义类型
interface HelloWorldProps {
title: string; //传字符串
age?: number; //传数字
render?: (count:number) => React.ReactNode; //传函数 类似vue插槽
onChange?: (count:number) => void; //父元素给子元素传递方法
}
export const HelloWorld = (props: HelloWorldProps) => {
const { title, age, render, onChange } = props;
const [count, setCount] = useState(0);
const handleAdd = ()=>{
setCount(count+1);
onChange?.(count+1);
}
return (
<div>
<h1>{title}===== {count}</h1>
<p>Age: {age}</p>
{/* 把子组件属性通过render函数传递给父组件 */}
{render?.(count)}
<button onClick={handleAdd}>增加</button>
</div>
);
};
//父组件
import './index.css';
import { HelloWorld } from './components/index.tsx';
function App() {
return (
// 传递子组件count参数给render函数
<HelloWorld
title="Hello React!"
age={18}
render={(count)=><div style={{color:'red'}}>你好吗?{count}</div>}
// 传递函数给子组件
onChange={(count)=>console.log(count)}
/>
);
}
export default App;
4.状态管理 Hooks详解
1.useState
//count 状态变量 setCount更新函数 第一次渲染传入初始值 0
//为异步更新
const [count, setCount] = useState(0);
import { useState } from "react";
export const HelloWorld = () => {
const [info, setInfo] = useState({
age:0
});
const handleAdd = ()=>{
//错误写法
// info.age++
// //!因为是异步 这里info.age++ 但下面仍然传的是旧对象,数据不是响应式所以数据不会改变
// setInfo(info);
//正确写法 解构的方式传的是新对象
//对象写法
// setInfo({
// ...info,
// age: info.age + 1
// });
//函数写法 (推荐写法,后续可以联合useCallback使用)
setInfo((prevInfo)=>({
...prevInfo,
age: prevInfo.age + 1
}));
}
return (
<div>
<h1>你好 ===== {info.age}</h1>
<button onClick={handleAdd}>增加</button>
</div>
);
};