在单个HTML文件里用React+Antd写一个嵌套表单

试试用单个HTML文件,写一个简单的动态表单Demo
传送门:https://gitee.com/Idler8/observer/blob/main/example/form-react-replace-rcfieldform/index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <link
      href="https://unpkg.com/[email protected]/dist/reset.css"
      rel="stylesheet"
      type="text/css"
    />
    <script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/antd.min.js"></script>
    <script src="https://unpkg.com/@idler8/[email protected]"></script>
    <script src="https://unpkg.com/@idler8/[email protected]"></script>
  </head>

  <body>
    <div id="root"></div>
    <script type="text/babel">
      const {
        FormValidator,
        useFieldState,
        useFieldReader,
        useFieldTrigger,
        useFormValidator,
      } = ReactObserver;
      const { Space, Card, Input, Button } = antd;
      //这是个验证函数,验证当前字段值是Success
      function isSuccess(values, keys) {
        const value = keys.reduce(function (prev, key) {
          return prev?.[key];
        }, values);
        if (value !== "Success") return keys.join(".") + " not Success";
      }
      // 自己造一个UI样式
      function CustomInput({ name, label, rule }) {
        const [value, onChange, errResponse] = useFieldState(name, rule);
        return (
          <>
            <div>{label}</div>
            <Input
              value={value || ""}
              onChange={(e) => onChange(e.target.value)}
            />
            {errResponse && <div style={{ color: "red" }}>{errResponse}</div>}
          </>
        );
      }
      // 尝试一下列表
      function Classes() {
        const classes = useFieldReader("classes");
        const onChange = useFieldTrigger("classes");
        return (
          <>
            {classes?.map(function (cls, index) {
              return (
                <CustomInput
                  key={index}
                  name={["classes", index, "name"]}
                  label={"班级" + (index + 1)}
                  rule={isSuccess}
                />
              );
            })}
            <Button onClick={() => onChange((classes) => [...classes, {}])}>
              增加班级
            </Button>
          </>
        );
      }
      //这里拿一个表单
      function MyForm() {
        const values = useFieldReader();
        const onChange = useFieldTrigger();
        const validator = useFormValidator();
        const handleSubmit = () => {
          validator()
            .then((values) => {
              console.log("表单数据:", JSON.stringify(values));
              alert(JSON.stringify(values));
            })
            .catch((errors) => {
              console.log("出错了,错误信息是:", JSON.stringify(errors));
            });
        };
        React.useEffect(function () {
          onChange({ school: "SchoolName", classes: [{ name: "ClassName" }] });
        }, []);
        return (
          <Space direction="vertical" style={{ margin: 20 }}>
            <Card title="DEBUG">{JSON.stringify(values)}</Card>
            <Card title="学校">
              <CustomInput name="school" label="学校名称" />
              <Classes />
              <Button onClick={handleSubmit}>验证数据</Button>
            </Card>
          </Space>
        );
      }
      //给表单一个上下文
      function MyApp() {
        return (
          <FormValidator>
            <MyForm />
          </FormValidator>
        );
      }

      const container = document.getElementById("root");
      const root = ReactDOM.createRoot(container);
      root.render(<MyApp />);
    </script>
  </body>
</html>

你可能感兴趣的:(web前端,react.js,html,javascript)