0

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

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对象来自定义和配置每个组件的单独外观。但是,是否有可能,而不是以线性方式创建表单,我可以获得每个单独的元素并将它们放置在我想要的位置?

例如,我可能想要name字段 onpage1age字段 on page3。目前我能想到的唯一方法是编辑包的源以返回单个元素,而不是将它们包装到Form对象中。

也许有一些方法React可以从对象中询问和提取单个组件Form

谢谢

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

4

1 回答 1

0

不,没有办法将rjsf表单拆分为多个 UI 组件。您可以通过制作多个表单(多个 JSON Schema )来模拟该行为schema。根据您想要的组合输出的结构,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)}
/>

您还可以将子项传递到 Form 组件以呈现您自己的按钮(因此,如果表单实际上不提交,您可能不希望表单显示“提交”而不是“下一页”)。

请注意,如果您执行自定义按钮并制作“下一步”按钮,由于它发出的事件类型(用于验证和其他一些事情),它仍然必须是“提交”类型。尽管有人要求使提交按钮的文本/标题更易于操作...

于 2020-05-25T04:32:31.737 回答