react-jsonschema-form 自定义元素位置

react-jsonschema-form custom element position

使用 react-jsonschema-form [1] 我们可以从配置而不是代码动态渲染 React 组件。 IE。

const Form = JSONSchemaForm.default;
const schema = {
  title: "Test form",
  type: "object",
  properties: {
    name: {
      type: "string"
    },
    age: {
      type: "number"
    }
  }
};

ReactDOM.render((
  <Form schema={schema} />
), document.getElementById("app"));

并且我们可以使用 uiSchema 对象来自定义和配置每个组件的单独外观。但是,我是否可以获取每个单独的元素并将它们放置在我想要的位置,而不是以线性方式创建表单?

例如,我可能想要 page1 上的 name 字段和 page3 上的 age 字段。目前我能想到的唯一方法是将包的源代码编辑为 return 个单独的元素,而不是将它们包装到 Form 对象中。

也许 React 中有某种方法可以从 Form 对象中查询和提取各个组件?

谢谢

[1] https://react-jsonschema-form.readthedocs.io/en/latest/

不,没有办法让 rjsf 将表单拆分为多个 UI 组件。您可以通过创建多个表单(多个 JSON 架构 schemas)来模拟该行为。根据您想要的组合输出的结构,最简单的方法可能是将 schema 分解为根级别上明显的不同嵌套 属性,例如第一页对应于根级别的第一个键 (name),第二页对应于第二个键 (age),依此类推。请注意,您必须自己控制此分页和导航,并将每个页面的 formData 合并回您期望的单一有效负载。

这是草稿:

pageOneSchema = {
  title: "Test form pg. 1",
  type: "object",
  properties: {
    name: {
      type: "string"
    }
  }
};

pageTwoSchema = {
  title: "Test form pg. 2",
  type: "object",
  properties: {
    age: {
      type: "number"
    }
  }
};

const schemas = [pageOneSchema, pageTwoSchema];

// Your component's member functions to orchestrate the form and its "pages"
state = {
  currentPage: 0,
  pages: new Array(schemas.length).fill({}), // initial pages array to empty objects = unfilled forms
}

pageDataChangeHandler = (page) => {
  const onChange = (e) => {
    const pages = [...this.state.pages];
    pages[page] = e.formData; // not too 100% about the key
    this.setState({
      pages,
    });
  }
}

getSubmitHandlerForPage = (page) => {
  if (page !== schemas.length) {
    // If current page is not the last page, move to next page
    this.setState({
      currentPage: page + 1,
    });
  } else {
    // concat all the pages' data together to recompose the singular payload
  }
}

...
const { currentPage } = this.state; 
<Form
  formData={this.state.pages[currentPage]}
  schema={schemas[currentPage]}
  onChange={this.pageDataChangeHandler(currentPage)}
  onSubmit={this.getSubmitHandlerForPage(currentPage)}
/>

您也可以 pass children into the Form component to render your own buttons(因此,如果他们实际上不会提交,您可能不希望表单显示 "Submit" 而不是 "Next Page")。

请注意,如果您自定义按钮并制作一个 "Next" 按钮,它仍然必须是 "submit" 类型,因为它发出的事件类型(用于验证和其他一些事情) .虽然有人问 make the text/title of the submit button easier to manipulate...