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;