跳到内容

创建自定义布局

布局是一种特殊类型的组件,Swagger UI 将其用作整个应用程序的根组件。您可以定义自定义布局,以便对最终显示在页面上的内容进行高级控制。

默认情况下,Swagger UI 使用内置于应用程序中的 BaseLayout。您可以通过将布局的名称作为 layout 参数传递给 Swagger UI 来指定要使用的不同布局。请确保将您的自定义布局作为组件提供给 Swagger UI。


例如,如果您想创建一个仅显示操作的自定义布局,您可以定义一个 OperationsLayout

1
import React from "react"
2
3
// Create the layout component
4
class OperationsLayout extends React.Component {
5
render() {
6
const {
7
getComponent
8
} = this.props
9
10
const Operations = getComponent("operations", true)
11
12
return (
13
<div className="swagger-ui">
14
<Operations />
15
</div>
16
)
17
}
18
}
19
20
// Create the plugin that provides our layout component
21
const OperationsLayoutPlugin = () => {
22
return {
23
components: {
24
OperationsLayout: OperationsLayout
25
}
26
}
27
}
28
29
// Provide the plugin to Swagger-UI, and select OperationsLayout
30
// as the layout for Swagger-UI
31
SwaggerUI({
32
url: "https://petstore.swagger.io/v2/swagger.json",
33
plugins: [ OperationsLayoutPlugin ],
34
layout: "OperationsLayout"
35
})

增强默认布局

如果您想围绕 BaseLayout 构建而不是替换它,您可以将 BaseLayout 拉入您的自定义布局并使用它

1
import React from "react"
2
3
// Create the layout component
4
class AugmentingLayout extends React.Component {
5
render() {
6
const {
7
getComponent
8
} = this.props
9
10
const BaseLayout = getComponent("BaseLayout", true)
11
12
return (
13
<div>
14
<div className="myCustomHeader">
15
<h1>I have a custom header above Swagger-UI!</h1>
16
</div>
17
<BaseLayout />
18
</div>
19
)
20
}
21
}
22
23
// Create the plugin that provides our layout component
24
const AugmentingLayoutPlugin = () => {
25
return {
26
components: {
27
AugmentingLayout: AugmentingLayout
28
}
29
}
30
}
31
32
// Provide the plugin to Swagger-UI, and select AugmentingLayout
33
// as the layout for Swagger-UI
34
SwaggerUI({
35
url: "https://petstore.swagger.io/v2/swagger.json",
36
plugins: [ AugmentingLayoutPlugin ],
37
layout: "AugmentingLayout"
38
})