如何将React类组件转换为函数组件?附旧代码转换需求
React类组件转函数组件的标准方法及示例转换
标准转换步骤
- 将类声明替换为函数声明,直接导出函数组件,无需继承
React.Component - 使用
useState钩子替代类组件的state,初始化状态值 - 移除
constructor,函数组件通过参数直接接收props - 移除事件绑定代码(如
bind(this)),函数组件内的事件处理函数可直接定义,无需绑定上下文 - 使用
useState返回的状态更新函数替代setState - 移除
render方法,函数组件的返回值即为原render方法的内容 - 访问
props时直接使用函数参数,无需this.props
转换后的函数组件代码
import React, { useState } from 'react'; import { Button, Container, Row, Col } from 'reactstrap'; import { Redirect } from 'react-router-dom'; export const ClickPhoto = (props) => { const [clickPhoto, setClickPhoto] = useState(false); const handle = () => { sessionStorage.setItem('/camera', JSON.stringify(true)); sessionStorage.setItem(props.current, JSON.stringify(false)); setClickPhoto(true); }; if (clickPhoto) { return <Redirect to="/camera" />; } return ( <div className="text-center" style={{ marginTop: "15px", marginBottom: "15px" }}> <Container className="clickPhoto"> <Row> <Col><Button color="success" onClick={handle}>CLICK PHOTO</Button></Col> </Row> </Container> </div> ); };
关键转换点说明
- 状态管理:用
useState(false)替代类组件中constructor里的this.state = { clickPhoto: false },通过setClickPhoto更新状态 - 事件处理:直接定义
handle函数,无需bind(this),函数内可直接访问props - props访问:通过函数参数
props直接获取current属性,无需this.props - 条件渲染:逻辑与原组件一致,只是将
this.state.clickPhoto替换为clickPhoto状态变量 - 组件结构:移除类组件的
render方法,函数直接返回JSX内容
内容的提问来源于stack exchange,提问作者Siam Parvez
相关产品推荐
相关产品推荐

