如果发现一种使用 Javascript 和 clientside callbacks 的 hacky 解决方法。
例如,假设custom_styles.css 与此处的引导样式发生冲突:
.btn-primary {
background-color: red;
}
dbc.Button 也有一个设置background-color 的btn-primary 类,因此上面的样式会覆盖 Bootstrap 中的background-color。
您可以做的是在返回布局之前根据当前 url pathname 在文档中动态设置样式表。
可能看起来像这样:
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from dash import Dash
from dash.dependencies import Output, Input
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(
[
dcc.Location(id="url", refresh=False),
html.Div(id="page-content"),
dcc.Store(id="pathname"),
]
)
app1_layout = dbc.Button("Button", color="primary")
app2_layout = html.Button("Button", className="primary")
app.clientside_callback(
"""
function(pathname) {
document.querySelectorAll('link[rel="stylesheet"]').forEach(stylesheet => {
stylesheet.remove()
})
const link = document.createElement('link')
link.setAttribute("rel", "stylesheet")
if (pathname == "/page-2") {
link.setAttribute("href", "/assets/custom_styles.css")
} else {
link.setAttribute("href", "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css")
}
document.head.append(link)
return pathname
}
""",
Output("pathname", "data"),
Input("url", "pathname"),
)
@app.callback(
Output("page-content", "children"),
Input("pathname", "data"),
)
def display_page(pathname):
if pathname == "/page-2":
return app2_layout
return app1_layout
if __name__ == "__main__":
app.run_server()
当路径名更改并输出到Store 组件的data 属性时,将执行客户端回调。返回布局的常规回调将此属性作为输入,因此回调将在更改时触发。