我正在使用 dash 构建一个仪表板,每当单击特定数据点时,我都会在其中创建一个唯一的 url,如何将用户重定向到此创建的 url? 我使用下面给出的代码,每当有人单击任何数据点时,单击事件就会触发并执行回调函数。
app.layout = html.Div(children=[
html.H1(children='Plot'),
dcc.Graph(id='example-graph',
figure = plot()),
html.Div(id='dummy-div')
])
@app.callback(Output('dummy-div', 'childern'),
Input('graph', 'clickData'))
def redirect_to_url(clickData):
triggered_id = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
if triggered_id=='graph' and clickData is not None:
url = 'https:www.example.com'
# need to develop to a method to redirect to this url
最佳答案
带有clienside callback ,使用window.location
:
app.clientside_callback(
"""
function(clickData) {
if (clickData?.points?.length) {
const point = clickData['points'][0];
const path = point.customdata ?? 'fallbackPath';
const url = `https://example.com/${path}`;
window.location = url;
}
}
""",
Output('dummy-div', 'children'),
Input('example-graph', 'clickData'),
prevent_initial_call=True #
)
铌。此选项还允许在新选项卡中打开目标页面,只需将 window.location = url
行替换为:
window.open(url, '_blank');
或者,添加 dcc.Location()
布局中的组件,然后您可以使用基本回调更新其 href
属性:
app.layout = html.Div(children=[
dcc.Location(id='location'),
html.H1(children='Plot'),
dcc.Graph(id='example-graph', figure=plot()),
html.Div(id='dummy-div')
])
@app.callback(Output('location', 'href'),
Input('example-graph', 'clickData'),
prevent_initial_call=True)
def redirect_to_url(clickData):
# do something with clickData
url = 'https:www.example.com'
return url
需要注意的一些事项:
- 如果您只有一个
Input()
,则无需检查触发器 id(即条件iftriggered_id=='graph'
不是必需的) - 确保您的输入/输出 ID 与布局中的内容匹配(“graph”与“example-graph”)
- “每当点击特定数据点时”重定向用户意味着条件
clickData is not None
而不是clickData is None
<
关于python - 重定向到破折号中的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75725718/