Skip to content

Instantly share code, notes, and snippets.

@MarshalW
Last active May 6, 2022 04:14
Show Gist options
  • Save MarshalW/022ce4348ead1c48ebe3a41a3a692b94 to your computer and use it in GitHub Desktop.
Save MarshalW/022ce4348ead1c48ebe3a41a3a692b94 to your computer and use it in GitHub Desktop.
使用 formily 和 schema 定制界面示例

使用 formily 和 schema 定制界面示例

import { MemoryRouter as Router, Link, Switch, Route } from 'react-router-dom';

import { createSchemaField, FormProvider } from '@formily/react';
import { createForm } from '@formily/core';
import { FormItem } from '@formily/antd';

const Home = ({ name = '' }) => <h1>Home {name}</h1>;
const About = () => <h1>About</h1>;

const SchemaField = createSchemaField({
  components: {
    Home,
    About,
    FormItem,
  },
});

const routes: object[] = [
  {
    path: '/',
    exact: true,
    component: 'Home',
  },
  {
    path: '/about',
    component: 'About',
  },
];

function RouteSwitch(props: any) {
  const { routes = [] } = props;
  if (!routes.length) {
    return null;
  }

  return (
    <Switch>
      {routes.map((route: any, index: number) => {
        return (
          <Route
            key={index}
            path={route.path}
            exact={route.exact}
            render={() => {
              return (
                <FormProvider
                  form={createForm({
                    effects: () => {},
                  })}
                >
                  <SchemaField
                    schema={{
                      type: 'object',
                      properties: {
                        page: {
                          type: 'string',
                          'x-decorator': 'FormItem',
                          'x-component': route.component,
                        },
                      },
                    }}
                  />
                </FormProvider>
              );
            }}
          />
        );
      })}
    </Switch>
  );
}

const App = () => {
  return (
    <Router>
      <Link to="/">首页</Link>
      <Link to="/about">关于</Link>
      <RouteSwitch routes={routes} />
    </Router>
  );
};

export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment