Dash Callbacks如何获取Output ID列表或向回调函数传入静态变量
解决方案
你提到的两个方案中,第一个在回调内部直接获取绑定的Output列表不可行,Dash官方没有在回调运行时暴露对应元数据的接口,强行通过私有属性获取的写法兼容性极差,不建议使用。第二个方案的思路是成立的,且可以用更简洁的实现,无需单独定义类。
这里提供两种生产环境常用的实现方案:
方案1:闭包生成带上下文的回调函数(优先推荐)
通过回调工厂函数为每个回调实例绑定对应的names变量,不需要额外添加输入源,写法简洁且性能无额外损耗。
首先定义回调工厂:
def create_toggle_callback(names): def toggle_active_links(pathname, style): # 注意:这里的路径判断逻辑请和你实际注册的页面路径对齐,可自行调整 path_list = [pathname == name for name in names] # 修正原代码bug:list.insert()无返回值,需先操作再返回列表 path_list.insert(0, style) return path_list return toggle_active_links
绑定回调时替换原逻辑即可:
from itertools import chain # create the callback for the page path x = [Output(f"sideMenuSection{Section.buttonCount}Title", "style"), [Output(f"page-{name}-link", "active") for name in pages]] outputList = [*chain(*(e if isinstance(e, list) else [e] for e in x))] # Path Callback 传入当前pages生成绑定了对应names的回调函数 app.callback( outputList, [ Input("url", "pathname"), Input(f"sideMenuSection{Section.buttonCount}Title", "style") ], )(create_toggle_callback(pages))
方案2:通过dcc.Store传递静态参数
如果你需要在多个回调中共享该names列表,可以将其存入dcc.Store组件,作为State参数传入回调,State不会触发回调,仅作为额外参数传递:
- 首先在对应页面布局中添加Store组件:
import dash_core_components as dcc dcc.Store(id=f"section-{Section.buttonCount}-names", data=pages)
- 回调定义中添加对应的State参数:
app.callback( outputList, [ Input("url", "pathname"), Input(f"sideMenuSection{Section.buttonCount}Title", "style") ], [State(f"section-{Section.buttonCount}-names", "data")] )(toggle_active_links1)
该写法可以直接复用你原有的toggle_active_links1函数逻辑,无需修改函数内部代码。
内容的提问来源于stack exchange,提问作者Matan
相关产品推荐
相关产品推荐

