当前位置: 首页 > news >正文

react学习与使用

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;
http://www.jsqmd.com/news/1235892/

相关文章:

  • 为什么选择Tack?5个理由告诉你为什么这是最佳的Terraform Kubernetes部署方案
  • 2026南京玄武劳力士卡地亚欧米茄回收门店盘点 正规实体完整一览 - 融媒生活
  • 2026食品自动化产线选型指南:软包装抓取专用柔爪供应商推荐 - 品牌深度评测
  • HDVPSS VIP_PARSER寄存器配置实战:从手册到稳定视频采集代码
  • 如何5分钟快速掌握Twitch视频下载:小白也能上手的完整教程
  • 微软Build 2026 AI技术突破:自研模型与智能体演进
  • 重磅公示|2026年7月百达翡丽香港官方售后服务中心网点地址及电话 - 百达翡丽服务中心
  • 制造行业工厂工业设备维保相关
  • 紧急通知:2024Q3起,未部署AI工作流的工程师将面临37%岗位响应延迟风险(附合规迁移路径)
  • SSRS性能优化技巧:提升遥感图像分割效率的10个方法
  • 你的Copilot可能正在被“下毒”:AI编程工具遭遇提示注入攻击
  • 2026年 乳山行业供应链服务公司实力洞察 - 甄选服务推荐
  • 如何3分钟完成图表数据提取:WebPlotDigitizer开源工具完全指南
  • LuxCoreRender:免费开源物理渲染引擎的完整指南
  • 不同等级的服装瑕疵,AI怎么做到自动分类?
  • 新手电子鼓看这3点,3000-5500元电鼓实测,3款高性价比机型推荐
  • 丽水防水补漏10个高频问题解答:2026年新价格、免砸砖实测详解 - 吉林同城获客
  • 在职MBA盘点:兼顾灵活上课与企业实践项目毕业的项目 - 新闻快传
  • AndroidNavigation入门教程:5分钟实现Fragment嵌套管理
  • 第6章 多轮对话与上下文记忆|Redis分布式会话实战落地
  • 大连中山区易奢福 2026 探店实录,现在回收黄金什么价格无隐形扣费 - 肉松卷
  • 海口黄金回收避坑:鬼秤、提纯费、虚报价,实测靠谱门店清单 - 一日一测评
  • 终极PrismLauncher手柄配置指南:10分钟实现Minecraft手柄操控
  • 劳动感悟别写空话,真实细节才能通过审核
  • 5分钟快速上手Keep:开源AIOps告警管理平台完整指南 [特殊字符]
  • SE8403 Sync Buck 100V10A
  • 找工作选平台比较靠谱的有推荐吗:赶集招聘五维评价 - 资讯速览
  • 5分钟上手raylib国际化:让你的游戏支持全球玩家
  • 打造个性化轮播:使用LESS自定义jQuery.Flipster主题的完整教程
  • 500+实战案例深度解析:AI智能体框架如何重塑企业数字化转型