扩展现有组件

除了新增组件,在 amis 中还能扩展和修改现有组件。

扩展表单验证

如果默认的表单检测规则不满足需求,还可以通过代码的方式扩展。

JSSDK 中的用法:

  1. let amisLib = amisRequire('amis');
  2. amisLib.addRule(
  3. // 校验名
  4. 'isZXS',
  5. // 校验函数,values 是表单里所有表单项的值,可用于做联合校验;value 是当前表单项的值
  6. (values, value) => {
  7. if (
  8. value === '北京' ||
  9. value === '上海' ||
  10. value === '天津' ||
  11. value === '重庆'
  12. ) {
  13. return true;
  14. }
  15. return false;
  16. },
  17. // 出错时的报错信息
  18. '输入的不是直辖市'
  19. );

这样在配置中就能使用下面的验证方法

  1. "validations": {
  2. "isZXS": true
  3. }

在 React 的使用方法是类似的

  1. import {addRule} from 'amis';

同时支持多种类型编辑

在表单编辑中,每个 name 一般对应一种类型,如果这个 name 有多种类型,比如下面的例子中 id 的值有可能是字符串,也有可能是数字,但 type 只能设置为一种类型,这种情况如何处理?

```schema: scope=”body” { “type”: “form”, “mode”: “horizontal”, “body”: [ { “name”: “id”, “type”: “input-text”, “label”: “id” } ] }

  1. 有两种方式:
  2. ### 使用另一个名称作为状态
  3. ```schema: scope="body"
  4. {
  5. "type": "form",
  6. "mode": "horizontal",
  7. "body": [
  8. {
  9. "name": "idIsNumber",
  10. "type": "switch",
  11. "label": "id 是数字类型"
  12. },
  13. {
  14. "name": "id",
  15. "type": "input-text",
  16. "label": "id",
  17. "hiddenOn": "data.idIsNumber"
  18. },
  19. {
  20. "name": "id",
  21. "type": "input-number",
  22. "label": "id",
  23. "visibleOn": "data.idIsNumber"
  24. }
  25. ]
  26. }

可以看到在一个 form 中可以有两个 name 相同的组件,通过 hiddenOn 或 visibleOn 来控制同时只显示一个。

使用 PipeIn/PipeOut 方法

如果不想增加一个新的 name,在 JS SDK 或 React 还有更高级的处理方法,可以增加一个 name 同样为 id 的 switch,实现 PipeIn/PipeOut 函数来进行自动识别,下面是个示例:

  1. let amis = amisRequire('amis/embed');
  2. let amisScoped = amis.embed('#root', {
  3. type: 'page',
  4. title: '表单页面',
  5. // 可以通过去掉下面的注释来测试
  6. // data: {
  7. // id: 1
  8. // },
  9. body: {
  10. type: 'form',
  11. mode: 'horizontal',
  12. api: '/saveForm',
  13. body: [
  14. {
  15. type: 'switch',
  16. label: 'id 是数字',
  17. name: 'id',
  18. // pipeIn 返回的应该是这个组件所需的值,比如 switch 的返回值就应该是 true 或 false
  19. // 这里的 value 就是初始值,如果不设置将会是 undefined
  20. pipeIn: (value, data) => {
  21. if (typeof value === 'undefined') {
  22. return false;
  23. }
  24. return typeof value !== 'string';
  25. },
  26. // 这里的 value 是点击 switch 之后的值,比如打开就是 true,关闭就是 false
  27. pipeOut: (value, oldValue, data) => {
  28. if (value) {
  29. return 1; // 切换到数字之后的默认值
  30. } else {
  31. return 'id1'; // 关闭之后的默认值
  32. }
  33. }
  34. },
  35. {
  36. name: 'id',
  37. type: 'text',
  38. label: 'id',
  39. visibleOn:
  40. 'typeof data.id === "undefined" || typeof data.id === "string"'
  41. },
  42. {
  43. name: 'id',
  44. type: 'number',
  45. label: 'id',
  46. visibleOn: 'typeof data.id === "number"'
  47. }
  48. ]
  49. }
  50. });

不过这种写法的复杂度较高

修改组件标签

有些组件可以设置 wrapperComponent,比如 Form 下默认使用 form 标签,在浏览器中会自带回车提交功能,如果想去掉这个功能,可以将 wrapperComponent 设置为 div