React函数组件中如何替代类组件里的this关键字
React函数组件中如何替代类组件里的this关键字
嘿,我来帮你捋清楚把类组件转成函数组件时,怎么处理原来类里到处用的this~毕竟函数组件里根本没有this这个东西,得换个思路来写。
一、原来的this.props怎么换?
函数组件的props是直接作为参数传给组件函数的,所以不用再写this.props啦:
- 要么在组件定义时直接解构需要的props,比如
const MyComponent = ({ match, location, listValue }) => {},之后在组件内部直接用match、location这些变量就行。 - 要么直接把props作为参数接收,比如
const MyComponent = (props) => {},然后用props.match、props.location来访问。
二、原来的this.model怎么处理?
这得看this.model在类组件里到底是啥:
- 如果它是组件的状态(比如类里用
this.state.model存的):那在函数组件里用useStateHook来替代,定义好状态后直接用变量名访问就行。 - 如果它是类的实例变量(不是状态,只是存在
this上的普通变量,比如this.model = { ... }):那用useRefHook,通过ref.current来访问和修改它。
三、结合你的openDictionary方法举个例子
给你把类组件里的方法转成函数组件的写法,一看就懂:
类组件里的原方法
openDictionary = async () => { const { special, sysColumnName, label, listLabel, sysColumnId, columnId, } = this.model; const { match, location, listValue, } = this.props; // 后续业务逻辑... }
转成函数组件(假设model是内部状态)
import { useState } from 'react'; const MyComponent = ({ match, location, listValue }) => { // 初始化model状态,根据你的实际初始值调整 const [model, setModel] = useState({ special: '', sysColumnName: '', label: '', listLabel: '', sysColumnId: '', columnId: '' }); const openDictionary = async () => { // 直接从model里解构属性,不用this const { special, sysColumnName, label, listLabel, sysColumnId, columnId, } = model; // props里的变量直接用,因为已经解构到组件参数里了 console.log(match, location, listValue); // 后续业务逻辑... }; // 组件渲染内容 return ( <div> <button onClick={openDictionary}>打开字典</button> {/* 其他JSX */} </div> ); };
如果model是实例变量(非状态)
import { useRef } from 'react'; const MyComponent = ({ match, location, listValue }) => { // 用useRef存实例变量,current属性就是实际值 const modelRef = useRef({ special: '', sysColumnName: '', // 其他初始属性 }); const openDictionary = async () => { const { special, sysColumnName, label, listLabel, sysColumnId, columnId, } = modelRef.current; // 后续逻辑... }; return <div>{/* 渲染内容 */}</div>; };
额外小提示
函数组件里的事件处理函数直接定义在组件内部就行,不用像类组件那样担心this指向的问题,也不需要手动bind,省了不少麻烦~
内容来源于stack exchange
相关产品推荐
相关产品推荐

