我只想知道是否可以将类组件转换为关于以下上下文的功能组件。我不明白/不知道的主要事情:
在 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() 时,组件就会弹出。我想知道是否可以对功能组件做同样的事情。