我尝试将基于类的组件转换为功能组件,但效果不佳

时间:2020-06-05 05:47:11

标签: javascript reactjs react-functional-component react-portal

我只是想知道是否有可能根据以下上下文将类组件转换为功能组件。我不了解/不了解的主要内容:

在RCC下面的上下文中,有一个静态方法create()和一个未绑定方法show(),如何在RFC中执行相同的操作?我可以像调用普通函数一样在其他任何组件中调用show函数。例如在fetch(url).then(data=>data.payload).catch(err=>settingsService.show())

文件:

SettingsDialog \ Settings.jsx,
SettingsDialog \ settingsService.jsx

Settings.jsx代码:

import React, { Component, forwardRef } from 'react';
import { render } from 'react-dom';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import Paper from '@material-ui/core/Paper';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import axios from "axios";

const url  = `http://localhost:8081/api/role`; 


let resolve;

class Settings extends Component {

static create() {
    const containerElement = document.createElement('div');
    document.body.appendChild(containerElement);
    return render(<Settings/>, containerElement);
  }


 constructor() {
   super();
   this.state = {
     isOpen: false,
     checked: false,
     data: []
   };

    this.handleCancel = this.handleCancel.bind(this);
    this.handleConfirm = this.handleConfirm.bind(this);
    this.handleSelectionProps = this.handleSelectionProps.bind(this);
 }


 handleCancel() {
    this.setState({isOpen: false});
    resolve(false);
  }

  handleConfirm() {
    this.setState({isOpen: false});
    resolve(true);
  }

  handleSelectionProps(rowData){
    return {
      disabled:
      this.state.checked && this.state.checked.length >= 2 && !rowData.tableData.checked
          ? true
          : false
    };
  };

  show(title,content) {
    this.setState({isOpen: true});
    axios.get(url).then(response => {
      this.setState({data:response.data.payload});
      console.log(response);
    })
    .catch(error => {console.error(error);this.setState({data:[]})});
    return new Promise((res) => {
      resolve = res;
    });
  }


 render() {


   const { isOpen } = this.state;
   return(
    <Dialog open={isOpen} onClose={this.handleCancel} aria-labelledby="form-dialog-title">
      <DialogContent>
       <p>Dialog content</p>
        </DialogContent>
        <DialogActions>
          <Button onClick={this.handleConfirm}color="primary" variant="contained">
            OK
          </Button>
        </DialogActions>
      </Dialog>
    )
    }
} export default Settings;

settingsService.jsx代码:

import Settings from './Settings';
export default Settings.create();

每当我调用settingsService.show()时,组件就会弹出。我想知道是否可以对功能组件执行相同的操作。

0 个答案:

没有答案
相关问题