在react-admin
中,我想创建一个切换按钮,根据数据库的默认值,允许用户更改状态并在Show
和后端进行相应的更改数据库中。
目前我的代码如下所示:
default class Deploy extends React.Component<{ data: any }> {
handleClick = () => {
const status = this.props.data.status;
alert(status);
};
render() {
const status = this.props.data.status;
return (
<Fragment>
<Button color="primary" onClick={this.handleClick}>
<ActionEject />
{status === "DEPLOYED" ? "UNDEPLOY" : "DEPLOY"}
</Button>
</Fragment>
);
}
}
class Actions extends React.Component<{ basePath: any; data: any; resource: any }, any> {
render() {
const basePath = this.props.basePath;
const data = this.props.data;
const resource = this.props.resource;
if (this.props.data) {
const defaultValue = this.props.data.default;
return (
<Deploy data={data} />
);
}
return null;
}
}
export default class ModelShow extends React.Component {
render() {
return (
<Show title={<ModelName />} actions={<Action />} {...this.props}>
<TabbedShowLayout>
<Tab label="Summary">
<TextField source="id" />
<TextField source="status" />
</Tab>
</TabbedShowLayout>
</Show>
);
}
}
P.S:我正在使用Typescript。
答案 0 :(得分:1)
您可以在Actions
的文档中找到多个示例为了正确更新react-admin状态,您应该遵循使用数据提供程序而不是获取示例或使用自定义操作创建程序示例。
以下是直接使用dataProvider的示例:
// Import the UPDATE verb
import { UPDATE } from 'react-admin';
// Import your dataProvider
import dataProvider from '../dataProvider';
default class Deploy extends React.Component<{ data: any }> {
handleClick = () => {
const status = this.props.data.status;
const { push, record, showNotification } = this.props;
const updatedRecord = { ...record, status };
dataProvider(UPDATE, 'you_resource_name', { id: record.id, data: updatedRecord })
.then(() => {
// Optional notification
showNotification('Resource deployed');
// Optional redirection to the list page
push('/you_resource_name');
})
.catch((e) => {
console.error(e);
showNotification('Error: resource not deployed', 'warning')
});
};
render() {
const status = this.props.data.status;
return (
<Fragment>
<Button color="primary" onClick={this.handleClick}>
<ActionEject />
{status === "DEPLOYED" ? "UNDEPLOY" : "DEPLOY"}
</Button>
</Fragment>
);
}
}