尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

react学习与使用

react学习与使用
📅 发布时间:2026/7/21 17:12:34

1.useState用法

1.1.基本数据类型

//实时获取值const[count,setCount]=useState(0);useEffect(()=>{console.log(count);},[count]);consthandleClick=()=>{setCount(count=>count+1)}

1.2.引用数据类型

//useState返回一个数组,数组里有两项const[myState,setMyState]=useState({curNodeName:'',recordVisible:false});const[arr,setArr]=useState([{width:10,id:0}]);constupdateMyState=data=>{setMyState({...myState,...data});};constdealState=(nodeId:number)=>{//改变对象里的值updateMyState({recordVisible:true})//增加setArr([...arr,{width:10,id:count+1}]);//删除setArr(arr.filter((item,i)=>i!==index));// 修改索引为index的元素setArr(arr.map((item,i)=>i===index?{...item,width:newWidth,id:newId}:item));}

2.redux用法

reducers:用于同步更新状态,reducer 通过接受 action 来更新状态。 effects:处理异步操作,通过yield关键字来进行异步请求,结合select,call,put使用。 dispatch:触发同步和异步的 action,dispatch 会通知 reducer 或 effect 执行相应的操作。exportdefault{namespace:"myModel",// 模块唯一标识,页面dispatch必须带上state:{tableList:[],current:1,pageSize:10,totalNum:0,},reducers:{// 同步更新state,payload可以传tableList/current/total等多个字段setTableList(state,{payload}){return{...state,// 保留原有state其他字段...payload// 覆盖传入的字段}}},effects:{// 异步方法,* 生成器,yield 阻塞等待异步完成*getList({payload},{select,call,put}){// 1. select 获取当前 myModel 下的 state(示例,本逻辑没用到)conststate=yieldselect(state=>state['myModel'])// 2. call 发起接口请求,payload是页面传过来的分页参数constresponse=yieldcall(getTableList,payload);// 3. put 派发同步action,执行reducer里的setTableList更新页面状态yieldput({type:'setTableList',payload:{tableList:Object.assign([],response.data.records),current:Number(response?.data?.current)||1,pageSize:Number(response?.data?.size)||10,totalNum:Number(response?.data?.total)||0,}})}},subscriptions:{},// 监听路由/浏览器事件,这里没用到留空};//页面使用时import{useSelector,useDispatch}from'react-redux';constdispatch=useDispatch();dispatch({type:`myModel/getList`,payload:{}});//页面获取值时constselector=useSelector(state=>state['myModel'])

3.父子组件传值

3.1.父传子(props)

//父组件importReactfrom'react';importChildComponentfrom'./ChildComponent';constParentComponent:React.FC=()=>{// 定义需要传递的数据constmessage='这是来自父组件的数据';// 定义需要传递的方法consthandleClick=()=>{console.log('按钮被点击了');};return(<div>{/* 传递数据和方法给子组件 */}<ChildComponent text={message}onClick={handleClick}/></div>);};
//子组件importReactfrom'react';interfaceChildProps{text:string;onClick:()=>void;}constChildComponent:React.FC<ChildProps>=(props)=>{return(<div><p>{props.text}</p><button onClick={props.onClick}>点击我</button></div>);};

3.2.子传父(ref)

//父组件不管是类还是函数组件都支持creatRef(),函数组件可以用useRef();//子组件中,函数组件由于没有实例,只能使用forwardRef搭配useImperativeHandle使用importReact,{useImperativeHandle,forwardRef}from'react';constfocusInput=()=>{console.log('Input is focused');}constChildComponent=forwardRef((props,ref)=>{useImperativeHandle(ref,()=>{return{focusInput}});});
//子组件importReact,{useRef}from'react';importChildComponentfrom'./ChildComponent';functionParentComponent(){constchildRef=useRef(null);consthandleClick=()=>{if(childRef.current){childRef.current.focusInput();// 调用子组件的方法}};return(<div><ChildComponent ref={childRef}/><button onClick={handleClick}>Focus Input</button></div>);}

3.3子组件改变父组件的值
1.通过回调函数的方式

// 父组件importReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[parentValue,setParentValue]=useState('');// 定义更新父组件状态的函数constupdateParentValue=(newValue)=>{setParentValue(newValue);};return(<div><p>父组件的值:{parentValue}</p>{/* 将更新函数作为prop传递给子组件 */}<ChildComponent onUpdateValue={updateParentValue}/></div>);};// 子组件constChildComponent=({onUpdateValue})=>{consthandleChange=(event)=>{// 调用父组件传递的函数,更新父组件的值onUpdateValue(event.target.value);};return(<input type="text"placeholder="输入内容更新父组件的值"onChange={handleChange}/>);};

2.通过context的方式

importReact,{createRef,createContext,useState}from'react';importTablePagefrom'./table';// 父组件(Provider)exportconstValueContext=createContext<any>(null);constEntry:React.FC<any>=props=>{const[parentValue,setParentValue]=useState('');constvalueContextValue={parentValue,setParentValue};return(<ValueContext.Provider value={valueContextValue}><p>父组件的值:{parentValue}</p><TablePage/></ValueContext.Provider>);};exportdefaultEntry;
//子组件importReact,{forwardRef,useContext}from'react';import{ValueContext}from'./index';classConfigSummaryProps{disabled?:boolean;[p:string]:any;}typeConfigSummaryRef={getEditData:()=>any;};constConfigSummary=forwardRef<ConfigSummaryRef,ConfigSummaryProps>((props,ref)=>{})//ts写法constTablePage:React.FC<any>=forwardRef((props,ref)=>{const{parentValue,setParentValue}=useContext(ValueContext);consthandleChange=(event)=>{setParentValue(event.target.value);};return(<><input type="text"placeholder="输入内容更新父组件的值"onChange={handleChange}/></>);});exportdefaultTablePage;

相关新闻

  • 2026食品自动化产线选型指南:软包装抓取专用柔爪供应商推荐 - 品牌深度评测
  • 重磅公示|2026年7月百达翡丽香港官方售后服务中心网点地址及电话 - 百达翡丽服务中心
  • 丽水防水补漏10个高频问题解答:2026年新价格、免砸砖实测详解 - 吉林同城获客

最新新闻

  • Python 与量子计算中级教程
  • 权威通告:雅典绍兴官方2026年7月最新网点地址及售后热线,服务信息一览 - 亨得利钟表维修中心
  • Claude Code 保姆级教程:AI 编码代理安装配置与实战指南
  • 长途电动车托运避坑指南:2026年寄运套路拆解与优选物流方案解析 - 快递物流资讯
  • Umi-OCR完全指南:3步掌握免费离线文字识别技巧
  • 液压阀生产厂家怎么选?看这3点就够了 - GrowUME

日新闻

  • Python开发内部工具:7大核心库实战解析
  • 合肥雷达官方2026年7月最新信息:客户服务网点地址与售后热线权威公示 - 亨得利官方服务中心
  • PCA实战指南:从变量纠缠诊断到主成分业务解读

周新闻

  • SaaS软件行业GEO实践:AI搜索时代的品牌可见性与获客新路径
  • 什么是PCTFE?医药高端包装的“防潮王牌“材料
  • 【JVM调优实战】16-可视化利器-JConsole-VisualVM-JMC

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号