簡體   English   中英

如何在反應中將 class 組件轉換為功能組件?

[英]How to convert class components to functional component in react?

如何將這部分代碼轉換為反應功能組件? 這是一段非常古老的代碼,我必須將其轉換為功能組件。 需要知道這樣做的標准方法。

import React from 'react';
import { Button, Container, Row, Col } from 'reactstrap';
import {Redirect} from 'react-router-dom';

export class ClickPhoto extends React.Component{

    constructor(props){
        super(props);
        this.state={
            clickPhoto:false
        }
        this.handle=this.handle.bind(this);
    }
    handle(){
        sessionStorage.setItem('/camera',JSON.stringify(true));
        sessionStorage.setItem(this.props.current,JSON.stringify(false));
        this.setState({
            clickPhoto:true
        })
    }
    render(){
        if(this.state.clickPhoto===true){
            return <Redirect to="/camera"/>
        }
        else{
            return (
                <div className="text-center" style={{marginTop:"15px",marginBottom:"15px"}}>
                <Container className="clickPhoto">
                    <Row>
                        <Col><Button color="success" onClick={this.handle}>CLICK PHOTO</Button></Col>
                    </Row>
                </Container>
                </div>
            );
        }
    }
};
```

您可以編寫如下功能組件

import React, {useState} from 'react';
...
const ClickPhoto = (props) => {
  const[clickPhoto, setClickPhoto] = useState(false);

  const handle = () =>{
    sessionStorage.setItem('/camera',JSON.stringify(true));
    sessionStorage.setItem(this.props.current,JSON.stringify(false));
    setClickPhoto(true);
  }

  return clickPhoto ? (<Redirect to="/camera"/>)
  : (
    <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>
);

}

以下是步驟:

  1. 使用 function 代替 class
  2. 刪除構造函數
  3. 去掉 render() 方法,保留返回
  4. 在所有方法之前添加 const
  5. 在整個組件中刪除 this.state
  6. 刪除整個組件中對“this”的所有引用
  7. 使用 useState() 設置初始 state
  8. 更改 this.setState() ...改為調用您在上一步中命名的 function 以更新狀態...
  9. 用 useEffect 替換 compentDidMount
  10. 用 useEffect 替換 componentDidUpdate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM