Dash㊴(Linkコンポーネント)

Linkコンポーネント

Linkコンポーネントを使うと、他ページへのリンクを作成することができます。

リンクの設定値は次の通りです。

オプション データ型 内容
第一引数 文字列 ハイパーリンクを設定。
href 文字列 リンク先のURLを設定。
refresh ブール型 リンクをクリックした時にページを更新するかどうか。
デフォルトはFalse。

今回は、リンクが3つあるアプリケーションを作成します。

[ソースコード]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__) # Dashインスタンスを生成

app.layout = html.Div(
[
dcc.Location(id='location1'),
html.Br(),
dcc.Link('/test1', href='/test1'),
html.Br(),
dcc.Link('/test2', href='/test2'),
html.Br(),
dcc.Link('/test3', href='/test3'),
html.Br(),
html.Br(),
html.Div(
id='div1',
style={'fontSize':'40', 'textAlign':'center', 'height':350}
)
],
style={'fontSize':'40', 'textAlign':'center'}
)

# コールバックの定義
@app.callback(
Output('div1', 'children'),
Input('location1', 'pathname')
)
def update_location(pathname):
# pathnameごとにコンテンツを返す
if pathname == '/test1':
return html.H1('test1のページ')
elif pathname == '/test2':
return html.H2('test2のページ')
elif pathname == '/test3':
return html.H3('test3のページ')
else:
return '初期画面'

if __name__ == '__main__':
app.run_server(debug=True) # アプリケーションを起動

コールバック関数では、クリックされたリンクに応じてDivコンポーネントに文字列を設定しています。

[ブラウザで表示]

リンクをクリックすると、Divコンポーネントの文字列が変わることを確認できます。