環境準備で、ボタンをクリックした分だけカウントしてくれる WEB アプリが起動できたと思います。
ここでは、その起動した WEB アプリでスクラッチで書き直していきます。
フロントエンドはmy_component/frontend/src/MyComponent.tsx、バックエンドはmy_component/__init__.pyを書き直していきます。
import {
Streamlit,
StreamlitComponentBase,
withStreamlitConnection,
} from "streamlit-component-lib"
import React, { ReactNode } from "react"
interface State {
numClicks: number
}
/**
* This is a React-based component template. The `render()` function is called
* automatically when your component should be re-rendered.
*/
class MyComponent extends StreamlitComponentBase<State> {
public state = { numClicks: 0, isFocused: false }
public render = (): ReactNode => {
// Arguments that are passed to the plugin in Python are accessible
// via `this.props.args`. Here, we access the "name" arg.
const name = this.props.args["name"]
const greeting=this.props.args["greeting"]
// Streamlit sends us a theme object via props that we can use to ensure
// that our component has visuals that match the active theme in a
// streamlit app.
const { theme } = this.props
const style: React.CSSProperties = {}
// Maintain compatibility with older versions of Streamlit that don't send
// a theme object.
if (theme) {
// Use the theme object to style our button border. Alternatively, the
// theme style is defined in CSS vars.
const borderStyling = `1px solid ${
this.state.isFocused ? theme.primaryColor : "gray"
}`
style.border = borderStyling
style.outline = borderStyling
}
// Show a button and some text.
// When the button is clicked, we'll increment our "numClicks" state
// variable, and send its new value back to Streamlit, where it'll
// be available to the Python program.
return (
<span>
<button
style={style}
onClick={this.onClicked}
disabled={this.props.disabled}
>
Click Me!
</button>
</span>
)
}
/** Click handler for our "Click Me!" button. */
private onClicked = (): void => {
// Increment state.numClicks, and pass the new value back to
// Streamlit via `Streamlit.setComponentValue`.
this.setState(
prevState => ({ numClicks: prevState.numClicks + 1 }),
() => Streamlit.setComponentValue(this.state.numClicks)
)
}
}
// "withStreamlitConnection" is a wrapper function. It bootstraps the
// connection between your component and the Streamlit app, and handles
// passing arguments from Python -> Component.
//
// You don't need to edit withStreamlitConnection (but you're welcome to!).
export default withStreamlitConnection(MyComponent)
ブラウザに返す button の HTML 要素を指定しています。
{greeting}と{name}は上記の変数 name, greeting の値を HTML として埋め込んでいます。
private onClicked = (): void => {
// Increment state.numClicks, and pass the new value back to
// Streamlit via `Streamlit.setComponentValue`.
this.setState(
prevState => ({ numClicks: prevState.numClicks + 1 }),
() => Streamlit.setComponentValue(this.state.numClicks)
)
}