plotly-dash - 如何从客户端回调返回 HTML / 组件?
问题描述
我想将常规(Python)回调转换为客户端。我在输出比children
简单字符串更复杂的属性时遇到了困难。
希望我可以用 来创建一个新组件new dash_html_components.Span()
,但这会引发错误:
Error: An object was provided as `children` instead of a component, string, or number (or list of those). Check the children property that looks something like:
{
"type": "span",
"key": null,
"ref": null,
"props": {
"children": "You have clicked THE Button!"
},
"_owner": null
}
完整代码如下。可以将字符串以外的任何内容设置为children
这样,或者我做错了什么?
import dash_html_components as html
from dash import Dash
from dash.dependencies import Output, Input
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
html.Button("THE Button", id="the_button"),
html.Div(id="the_log"),
])
app.clientside_callback(
"""
function(n_clicks){
// return "You have clicked THE Button!"; // works
// return "You have clicked <strong>THE Button!</strong>"; // works, but escapes the HTML (as expected)
return new dash_html_components.Span({children: "You have clicked THE Button!"}); // doesn't work
// return ["You have clicked ", new dash_html_components.Strong({children: "THE Button!" })]; // the goal
}
""",
Output("the_log", "children"),
Input("the_button", "n_clicks"),
)
if __name__ == '__main__':
app.run_server()
解决方案
如果您只需要编写内联 HTML 代码,则可以Purify
使用dash-extensions
. 当您将 HTML 代码传递给它的html
属性时,它会内联呈现,
from dash import html, Dash, Output, Input
from dash_extensions import Purify
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Click me", id="btn"), Purify(id="purify")])
app.clientside_callback("""function(n_clicks){return 'This is <b>html</b>';}""",
Output("purify", "html"), Input("btn", "n_clicks"))
if __name__ == "__main__":
app.run_server()
在渲染之前,使用DOMPurify执行清理,因此是组件的名称。
推荐阅读
- elasticsearch - 如何标记代表事件发生时间的字段?
- vba - 处理子例程中重复出现的 VBA 错误
- import - 在第 4 行声明标题
- python - Tkinter GUI 无法启动 - 线程 - Tkinter 对象没有属性“标签”
- javascript - 如何在 JavaScript 中定义的 x、y 坐标处模拟点击?
- r - ggplot:为什么 scale_x_date 需要 date_labels 中的附加元素?
- python - 如何在python中使用Ctypes最小化窗口
- java - 为什么 spring-cloud-starter-config 忽略 bootstrap.properties?
- java - 尽管 ListView 和 SimpleAdapter 有数据,Android ListView 不显示项目
- c++ - 如何在 C++ 中将二维数组转换为一维?