当前位置: 首页 > Web前端 > HTML

通过vue学习react(四)——watch、computed、slot等函数

时间:2023-03-28 18:02:00 HTML

这些功能比较简单,都是通过reacthooks和reactclass来实现的。如果你喜欢它,请喜欢它。React实现watchreacthook并实现watchfunctionuseWatch(deps:T,handler:(next:T,prev:T)=>void,immediate=false){letnextRef=useRef();constisImmediate=useRef(true);useEffect(()=>{if(isImmediate.current){handler(nextRef.currentasT,deps);}else{isImmediate.current=true;}return()=>{nextRef.current=deps;};},[deps]);}#使用let[count,setCount]=useState(0);useWatch(count,(next:typeofcount,prev:typeofcount)=>{console.log(next,prev);});React类写法实现watchclassWatchextendsReact.Component{state={count:0};构造函数(道具:FC){超级(道具);}setCount(){this.setState({count:this.state.count+1,});}componentDidUpdate(_prev:any,prevState:typeofthis.state){console.log(prevState.count,this.state.count);}render(){返回(

按钮
);}}react实现插槽(slot)reacthooks版本functionChild({children}:{children:React.ReactNode}){return(
child{children}
);}exportdefaultfunctionSlot(){return(

2333

);}react类写法classChildextendsReact.Component{render(){const{children}=this.props;返回(
孩子{孩子}
);}}classNameextendsReact.Component{constructor(props:React.FC){super(props);}render(){return(

2333

);}}react实际计算reacthooks版本通过useMemo模拟即可导出默认函数Computed(){let[count,setCount]=useState(0);constgetCount=useMemo(()=>{返回计数*2;},[数数]);return(
{getCount}{setCount(count+1);}}>button
);}react类的写法原理是每一个setState都会触发render,然后重新获取newCountclassNameextendsReact.Component{state={count:0};构造函数(道具:React.FC){超级(道具);}getnewCount(){返回这个.state.count+1;}render(){return(

{this.newCount}

);}}react实现v-modelreacthooksversioninterfaceformProps{name?:string;age?:string;}exportdefaultfunctionModel(){const[form,setForm]=useState({});consthandleChange=useCallback((e:ChangeEvent,key)=>{setForm((raw)=>({...raw,[key]:e.target.value}));},[]);函数onClick(){console.log(form);}返回(
handleChange(e,"name")}/>handleChange(e,"age")}/>按键
);}react类写法interfaceformProps{name?:细绳;age?:string;}classModelextendsReact.Component{构造函数(props:React.FC){super(props);this.state={形式:{}};}handleChange(e:React.ChangeEvent,key:string){this.setState({form:{...this.state.form,[key]:e.target.value},});}onClick=()=>{console.log(this.state.form);};render(){const{form}=this.state;return(
this.handleChange(e,"name")}/><输入类型="text"value={form.age??""}onChange={(e)=>this.handleChange(e,"age")}/>按钮
);}}react实践cssscopedcss模块#index.module.css.app{color:aqua;flex:1;}#Css.tsximportStylefrom"./index.module.css";exportdefaultfunctionCss(){return(
我是一个字段

);}cssinjs(emotion)安装npmi@emotion/styled@emotion/react使用/*@jsxImportSource@emotion/react*/importstyledfrom"@emotion/styled";import{css}来自“@emotion/react”;从“./index.module.css”导入样式;constbase=css`color:#ee298c;`;constContainer=styled.div`padding:23px;&:hover{颜色:${(props)=>props.color};}`;导出默认函数Css(){return(我是一个字段

测试

23333

);