title: 快速开始

description:

amis 有两种使用方法:

  • JS SDK,可以用在任意页面中
  • React,可以用在 React 项目中

SDK 版本适合对前端或 React 不了解的开发者,它不依赖 npm 及 webpack,可以像 Vue/jQuery 那样外链代码就能使用。

SDK

下载方式:

  1. github 的 releases,文件是 sdk.tar.gz。
  2. 使用 npm i amis 来下载,在 node_modules\amis\sdk 目录里就能找到。

新建一个 hello.html 文件,内容如下:

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>amis demo</title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7. <meta
  8. name="viewport"
  9. content="width=device-width, initial-scale=1, maximum-scale=1"
  10. />
  11. <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
  12. <link rel="stylesheet" href="sdk.css" />
  13. <link rel="stylesheet" href="helper.css" />
  14. <link rel="stylesheet" href="iconfont.css" />
  15. <!-- 这是默认主题所需的,如果是其他主题则不需要 -->
  16. <!-- 从 1.1.0 开始 sdk.css 将不支持 IE 11,如果要支持 IE11 请引用这个 css,并把前面那个删了 -->
  17. <!-- <link rel="stylesheet" href="sdk-ie11.css" /> -->
  18. <!-- 不过 amis 开发团队几乎没测试过 IE 11 下的效果,所以可能有细节功能用不了,如果发现请报 issue -->
  19. <style>
  20. html,
  21. body,
  22. .app-wrapper {
  23. position: relative;
  24. width: 100%;
  25. height: 100%;
  26. margin: 0;
  27. padding: 0;
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div id="root" class="app-wrapper"></div>
  33. <script src="sdk.js"></script>
  34. <script type="text/javascript">
  35. (function () {
  36. let amis = amisRequire('amis/embed');
  37. // 通过替换下面这个配置来生成不同页面
  38. let amisJSON = {
  39. type: 'page',
  40. title: '表单页面',
  41. body: {
  42. type: 'form',
  43. mode: 'horizontal',
  44. api: '/saveForm',
  45. body: [
  46. {
  47. label: 'Name',
  48. type: 'input-text',
  49. name: 'name'
  50. },
  51. {
  52. label: 'Email',
  53. type: 'input-email',
  54. name: 'email'
  55. }
  56. ]
  57. }
  58. };
  59. let amisScoped = amis.embed('#root', amisJSON);
  60. })();
  61. </script>
  62. </body>
  63. </html>

切换主题

jssdk 版本默认使用 sdk.css 即云舍主题,如果你想用使用仿 Antd,请将 css 引用改成 .antd.css。同时 js 渲染地方第四个参数传入 theme 属性。如:

  1. amis.embed(
  2. '#root',
  3. {
  4. // amis schema
  5. },
  6. {
  7. // 这里是初始 props
  8. },
  9. // 注意是第四个参数
  10. {
  11. theme: 'antd'
  12. }
  13. );

如果想使用 amis 1.2.2 之前的默认主题,名字是 ang

初始值

可以通过 props 里的 data 属性来赋予 amis 顶层数据域的值,类似下面的例子。

  1. let amis = amisRequire('amis/embed');
  2. let amisJSON = {
  3. type: 'page',
  4. body: {
  5. type: 'tpl',
  6. tpl: '${myData}'
  7. }
  8. };
  9. let amisScoped = amis.embed('#root', amisJSON, {
  10. data: {
  11. myData: 'amis'
  12. }
  13. });

控制 amis 的行为

amis.embed 函数还支持以下配置项来控制 amis 的行为,比如在 fetcher 的时候加入自己的处理逻辑,这些函数参数的说明在后面 React 中也有介绍。

  1. let amisScoped = amis.embed(
  2. '#root',
  3. amisJSON,
  4. {
  5. // 这里是初始 props,一般不用传。
  6. // locale: 'en-US' // props 中可以设置语言,默认是中文
  7. },
  8. {
  9. // 下面是一些可选的外部控制函数
  10. // 在 sdk 中可以不传,用来实现 ajax 请求,但在 npm 中这是必须提供的
  11. // fetcher: (url, method, data, config) => {},
  12. // 全局 api 请求适配器
  13. // 另外在 amis 配置项中的 api 也可以配置适配器,针对某个特定接口单独处理。
  14. //
  15. // requestAdaptor(api) {
  16. // return api;
  17. // }
  18. //
  19. // 全局 api 适配器。
  20. // 另外在 amis 配置项中的 api 也可以配置适配器,针对某个特定接口单独处理。
  21. // responseAdaptor(api, payload, query, request, response) {
  22. // return payload;
  23. // }
  24. //
  25. // 用来接管页面跳转,比如用 location.href 或 window.open,或者自己实现 amis 配置更新
  26. // jumpTo: to => { location.href = to; },
  27. //
  28. // 用来实现地址栏更新
  29. // updateLocation: (to, replace) => {},
  30. //
  31. // 用来判断是否目标地址当前地址。
  32. // isCurrentUrl: url => {},
  33. //
  34. // 用来实现复制到剪切板
  35. // copy: content => {},
  36. //
  37. // 用来实现通知
  38. // notify: (type, msg) => {},
  39. //
  40. // 用来实现提示
  41. // alert: content => {},
  42. //
  43. // 用来实现确认框。
  44. // confirm: content => {},
  45. //
  46. // 主题,默认是 default,还可以设置成 cxd 或 dark,但记得引用它们的 css,比如 sdk 目录下的 cxd.css
  47. // theme: 'cxd'
  48. //
  49. // 用来实现用户行为跟踪,详细请查看左侧高级中的说明
  50. // tracker: (eventTracker) => {},
  51. }
  52. );

同时返回的 amisScoped 对象可以获取到 amis 渲染的内部信息,它有如下方法:

getComponentByName(name) 用于获取渲染出来的组件,比如下面的示例

  1. {
  2. "type": "page",
  3. "name": "page1",
  4. "title": "表单页面",
  5. "body": {
  6. "type": "form",
  7. "name": "form1",
  8. "body": [
  9. {
  10. "label": "Name",
  11. "type": "input-text",
  12. "name": "name1"
  13. }
  14. ]
  15. }
  16. }

可以通过 amisScoped.getComponentByName('page1.form1').getValues() 来获取到所有表单的值,需要注意 page 和 form 都需要有 name 属性。

还可以通过 amisScoped.getComponentByName('page1.form1').setValues({'name1': 'othername'}) 来修改表单中的值。

更新属性

可以通过 amisScoped 对象的 updateProps 方法来更新下发到 amis 的属性。

  1. amisScoped.updateProps(
  2. {
  3. // 新的属性对象
  4. } /*, () => {} 更新回调 */
  5. );

多页模式

默认 amis 渲染是单页模式,如果想实现多页应用,请使用 app 渲染器

Hash 路由

默认 JSSDK 不是 hash 路由,如果你想改成 hash 路由模式,请查看此处代码实现。只需要修改 env.isCurrentUrlenv.jumpToenv.updateLocation 这几个方法,并在路由切换的时候,通过 amisScoped 对象的 updateProps 方法,更新 location 属性即可。

参考:https://github.com/baidu/amis/blob/master/examples/app/index.jsx

销毁

如果是单页应用,在离开当前页面的时候通常需要销毁实例,可以通过 unmount 方法来完成。

  1. amisScoped.unmount();

react

初始项目请参考 https://github.com/aisuda/amis-react-starter

如果在已有项目中,React 版本需要是 >=16.8.6,mobx 需要 ^4.5.0

amis 1.6.5 及以上版本支持 React 17。

安装

  1. npm i amis

webpack 配置参考

如果要使用代码编辑器,需要 monaco-editor-webpack-plugin 插件

  1. const path = require('path');
  2. const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
  3. const HtmlWebpackPlugin = require('html-webpack-plugin');
  4. const {CleanWebpackPlugin} = require('clean-webpack-plugin');
  5. const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
  6. module.exports = {
  7. mode: 'development',
  8. entry: {
  9. index: './src/index.tsx'
  10. },
  11. module: {
  12. rules: [
  13. {
  14. test: /\.tsx?$/,
  15. use: [
  16. {
  17. loader: 'ts-loader',
  18. options: {
  19. transpileOnly: true
  20. }
  21. }
  22. ],
  23. exclude: /node_modules/
  24. },
  25. {
  26. test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
  27. use: 'url-loader?limit=10000'
  28. },
  29. {
  30. test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
  31. use: 'file-loader'
  32. },
  33. {
  34. test: /\.css$/,
  35. use: ['style-loader', 'css-loader']
  36. },
  37. {
  38. test: /\.ttf$/,
  39. use: ['file-loader']
  40. }
  41. ]
  42. },
  43. plugins: [
  44. new CleanWebpackPlugin({cleanStaleWebpackAssets: false}),
  45. new HtmlWebpackPlugin({
  46. template: 'src/index.html'
  47. }),
  48. new MonacoWebpackPlugin(),
  49. new ForkTsCheckerWebpackPlugin()
  50. ],
  51. resolve: {
  52. extensions: ['.tsx', '.ts', '.js', '.html']
  53. },
  54. output: {
  55. filename: '[name].bundle.js',
  56. publicPath: '/'
  57. }
  58. };

主题样式

目前主要支持两个主题:cxd(云舍)antd(仿 Antd)

  1. 引入样式文件:

html 中引入:

  1. <link href="./node_modules/amis/lib/themes/cxd.css" />
  2. <link href="./node_modules/amis/lib/helper.css" />
  3. <link href="./node_modules/amis/sdk/iconfont.css" />
  4. <!-- 或 <link href="./node_modules/amis/lib/themes/antd.css" /> -->

js 中引入:

  1. import './node_modules/amis/lib/themes/cxd.css';
  2. import './node_modules/amis/lib/helper.css';
  3. import './node_modules/amis/sdk/iconfont.css';
  4. // 或 import './node_modules/amis/lib/themes/antd.css';

上面只是示例,请根据自己的项目结构调整引用路径 如果要支持 IE 11 请引入 ./node_modules/amis/sdk/cxd-ie11.css,但这样就没法支持 CSS 变量了

  1. 渲染器使用配置主题
  1. renderAmis(
  2. {
  3. type: 'page',
  4. title: '简单页面',
  5. body: '内容'
  6. },
  7. {
  8. // props
  9. },
  10. {
  11. // env...
  12. theme: 'cxd' // cxd 或 antd
  13. }
  14. );

使用指南

可以在 React Component 这么使用(TypeScript)。

  1. 安装部分示例需要的插件库
  1. npm i axios copy-to-clipboard

为了方便示例,上面选用了我们常用几个插件库,你完全可以选择自己喜欢的插件并重新实现

  1. 代码实现(React Typescript)
  1. import * as React from 'react';
  2. import axios from 'axios';
  3. import copy from 'copy-to-clipboard';
  4. import {render as renderAmis} from 'amis';
  5. import {ToastComponent, AlertComponent, alert, confirm, toast} from 'amis-ui';
  6. class MyComponent extends React.Component<any, any> {
  7. render() {
  8. let amisScoped;
  9. let theme = 'cxd';
  10. let locale = 'zh-CN';
  11. // 请勿使用 React.StrictMode,目前还不支持
  12. return (
  13. <div>
  14. <p>通过 amis 渲染页面</p>
  15. <ToastComponent
  16. theme={theme}
  17. key="toast"
  18. position={'top-right'}
  19. locale={locale}
  20. />
  21. <AlertComponent theme={theme} key="alert" locale={locale} />
  22. {renderAmis(
  23. {
  24. // 这里是 amis 的 Json 配置。
  25. type: 'page',
  26. title: '简单页面',
  27. body: '内容'
  28. },
  29. {
  30. // props...
  31. // locale: 'en-US' // 请参考「多语言」的文档
  32. // scopeRef: (ref: any) => (amisScoped = ref) // 功能和前面 SDK 的 amisScoped 一样
  33. },
  34. {
  35. // 下面三个接口必须实现
  36. fetcher: ({
  37. url, // 接口地址
  38. method, // 请求方法 get、post、put、delete
  39. data, // 请求数据
  40. responseType,
  41. config, // 其他配置
  42. headers // 请求头
  43. }: any) => {
  44. config = config || {};
  45. config.withCredentials = true;
  46. responseType && (config.responseType = responseType);
  47. if (config.cancelExecutor) {
  48. config.cancelToken = new (axios as any).CancelToken(
  49. config.cancelExecutor
  50. );
  51. }
  52. config.headers = headers || {};
  53. if (method !== 'post' && method !== 'put' && method !== 'patch') {
  54. if (data) {
  55. config.params = data;
  56. }
  57. return (axios as any)[method](url, config);
  58. } else if (data && data instanceof FormData) {
  59. config.headers = config.headers || {};
  60. config.headers['Content-Type'] = 'multipart/form-data';
  61. } else if (
  62. data &&
  63. typeof data !== 'string' &&
  64. !(data instanceof Blob) &&
  65. !(data instanceof ArrayBuffer)
  66. ) {
  67. data = JSON.stringify(data);
  68. config.headers = config.headers || {};
  69. config.headers['Content-Type'] = 'application/json';
  70. }
  71. return (axios as any)[method](url, data, config);
  72. },
  73. isCancel: (value: any) => (axios as any).isCancel(value),
  74. copy: content => {
  75. copy(content);
  76. toast.success('内容已复制到粘贴板');
  77. },
  78. theme
  79. // 后面这些接口可以不用实现
  80. // 默认是地址跳转
  81. // jumpTo: (
  82. // location: string /*目标地址*/,
  83. // action: any /* action对象*/
  84. // ) => {
  85. // // 用来实现页面跳转, actionType:link、url 都会进来。
  86. // },
  87. // updateLocation: (
  88. // location: string /*目标地址*/,
  89. // replace: boolean /*是replace,还是push?*/
  90. // ) => {
  91. // // 地址替换,跟 jumpTo 类似
  92. // },
  93. // isCurrentUrl: (
  94. // url: string /*url地址*/,
  95. // ) => {
  96. // // 用来判断是否目标地址当前地址
  97. // },
  98. // notify: (
  99. // type: 'error' | 'success' /**/,
  100. // msg: string /*提示内容*/
  101. // ) => {
  102. // toast[type]
  103. // ? toast[type](msg, type === 'error' ? '系统错误' : '系统消息')
  104. // : console.warn('[Notify]', type, msg);
  105. // },
  106. // alert,
  107. // confirm,
  108. // tracker: (eventTracke) => {}
  109. }
  110. )}
  111. </div>
  112. );
  113. }
  114. }

render 有三个参数,后面会详细说明这三个参数内的属性

  1. (schema, props, env) => JSX.Element;

schema

即页面配置,请前往 配置与组件 了解

props

一般都用不上,如果你想传递一些数据给渲染器内部使用,可以传递 data 数据进去。如:

  1. () =>
  2. renderAmis(schema, {
  3. data: {
  4. username: 'amis'
  5. }
  6. });

这样,内部所有组件都能拿到 username 这个变量的值。当然,这里的 key 并不一定必须是 data , 你也可以是其它 key,但必须配合 schema 中的 detectField 属性一起使用。 如:

  1. () =>
  2. renderAmis(
  3. {
  4. //其它配置
  5. detectField: 'somekey'
  6. },
  7. {
  8. somekey: {
  9. username: 'amis'
  10. }
  11. }
  12. );

env

环境变量,可以理解为这个渲染器工具的配置项,需要使用 amis 用户实现部分接口。他有下面若干参数:

fetcher(必须实现)

接口请求器,实现该函数才可以实现 ajax 发送,函数签名如下:

  1. (config: {
  2. url; // 接口地址
  3. method; // 请求方法 get、post、put、delete
  4. data; // 请求数据
  5. responseType;
  6. config; // 其他配置
  7. headers; // 请求头
  8. }) => Promise<fetcherResult>;

你可以使用任何你喜欢的 ajax 请求库来实现这个接口

notify

  1. (type: string, msg: string) => void

用来实现消息提示。

alert

  1. (msg: string) => void

用来实现警告提示。

confirm

  1. (msg: string) => boolean | Promise<boolean>;

用来实现确认框。返回 boolean 值

jumpTo

  1. (to: string, action?: Action, ctx?: object) => void

用来实现页面跳转,因为不清楚所在环境中是否使用了 spa 模式,所以用户自己实现吧。

updateLocation

  1. (location: any, replace?: boolean) => void

地址替换,跟 jumpTo 类似。

blockRouting

设置阻止路由跳转的钩子函数,用来实现 form 未保存提前离开时出现确认框。

  1. (fn: (nextLocation:any) => void | string) => () => void;

theme: string

目前支持是三种主题:defaultcxddark

isCurrentUrl

  1. (link: string) => boolean;

判断目标地址是否为当前页面。

copy

  1. (contents: string, options?: {silent: boolean, format?: string})

用来实现内容复制,其中 format 可以为 text/html,或 text/plain

tracker

用户行为跟踪,请参考这里

session

默认为 ‘global’,决定 store 是否为全局共用的,如果想单占一个 store,请设置不同的值。

getModalContainer

  1. () => HTMLElement;

用来决定弹框容器。

loadRenderer

  1. (schema: any, path: string) => Promise<Function>;

可以通过它懒加载自定义组件,比如: https://github.com/baidu/amis/blob/master/__tests__/factory.test.tsx#L64-L91。

affixOffsetTop: number

固顶间距,当你的有其他固顶元素时,需要设置一定的偏移量,否则会重叠。

affixOffsetBottom: number

固底间距,当你的有其他固底元素时,需要设置一定的偏移量,否则会重叠。

richTextToken: string

内置 rich-text 为 frolaEditor,想要使用,请自行购买,或者用免费的 Tinymce,不设置 token 默认就是 Tinymce。

hideValidateFailedDetail: boolean

Form 表单验证失败时在 notify 消息提示中是否隐藏详细信息,默认展示,设置为 true 时隐藏

replaceText

1.5.0 及以上版本

可以用来实现变量替换及多语言功能,比如下面的例子

  1. let amisScoped = amis.embed(
  2. '#root',
  3. {
  4. type: 'page',
  5. body: {
  6. type: 'service',
  7. api: 'service/api'
  8. }
  9. },
  10. {},
  11. {
  12. replaceText: {
  13. service: 'http://localhost'
  14. },
  15. replaceTextKeys: ['api']
  16. }
  17. );

它会替换 api 里的 service 字符串

replaceTextIgnoreKeys

1.5.0 及以上版本

和前面的 replaceText 配合使用,某些字段会禁用文本替换,默认有以下:

  1. type, name, mode, target, reload

如果发现有字段被意外替换了,可以通过设置这个属性来避免