You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dash应用中接入使用第三方开发的React组件?

第三方React组件接入Dash实操流程(以react-stars五星评分组件为例)

不需要掌握React/JS深度开发能力,按固定流程套模板即可完成复用,全程操作步骤如下:

环境准备

  • 安装Node.js LTS长期支持版,安装时勾选「Add to PATH」选项,安装完成后在终端执行node -v、npm -v能正常输出版本号即配置成功
  • Python环境安装依赖:执行pip install cookiecutter dash

生成组件项目模板

  • 终端进入你存放组件代码的目录,执行cookiecutter gh:plotly/dash-component-boilerplate拉取官方组件模板
  • 按终端提示填写项目信息:项目名填dash-react-stars,组件名填DashReactStars,作者、描述字段按需填写,其余选项全部选默认值即可
  • 模板生成完成后,进入新生成的dash-react-stars文件夹,执行npm install安装项目基础依赖

引入目标第三方React组件

  • 在当前项目目录的终端执行npm install react-stars --save,下载你需要复用的react-stars组件包
  • 打开路径src/lib/components/下的DashReactStars.react.js文件,清空原有默认示例代码,替换为以下固定适配代码:
import React from 'react';
import PropTypes from 'prop-types';
import ReactStars from 'react-stars';

const DashReactStars = (props) => {
    const {id, value, setProps, count, size, color2, edit} = props;

    const ratingChanged = (newRating) => {
        setProps?.({value: newRating})
    }

    return (
        <div id={id}>
            <ReactStars
                count={count}
                value={value}
                size={size}
                color2={color2}
                edit={edit}
                onChange={ratingChanged}
            />
        </div>
    )
}

DashReactStars.defaultProps = {
    value: 0,
    count: 5,
    size: 24,
    color2: '#ffd700',
    edit: true
};

DashReactStars.propTypes = {
    id: PropTypes.string,
    value: PropTypes.number,
    count: PropTypes.number,
    size: PropTypes.number,
    color2: PropTypes.string,
    edit: PropTypes.bool,
    setProps: PropTypes.func
};

export default DashReactStars;
  • 适配逻辑不需要自己写交互:所有你需要在Python端控制的组件参数,只要在defaultProps里设好默认值、在propTypes里声明参数类型,再传给引入的第三方React组件即可;组件自带的交互事件只要把返回值通过setProps同步给Dash的属性,就能实现和Dash回调的双向绑定。如果要加其他参数,直接查对应React组件的文档,按相同规则加就行。

编译安装组件到Python环境

  • 在项目根目录终端执行npm run build,等待编译完成,工具会自动生成Python可识别的组件包文件
  • 继续在当前目录执行pip install -e .,把组件安装到你当前使用的Python环境中

在Dash应用中调用

安装完成后,组件的使用方式和Dash官方内置组件完全一致,示例代码:

from dash import Dash, html, callback, Input, Output
import dash_react_stars

app = Dash(__name__)

app.layout = html.Div([
    html.H3("用户评分"),
    dash_react_stars.DashReactStars(
        id='rating',
        size=30,
        color2='#ff9900',
        edit=True,
        value=0
    ),
    html.Div(id='rating-result')
])

@callback(
    Output('rating-result', 'children'),
    Input('rating', 'value')
)
def show_score(score):
    return f"当前评分:{score} 星"

if __name__ == '__main__':
    app.run_server(debug=True)

该流程适配绝大多数开源React组件,不需要深入学习React技术栈,核心就是把第三方组件套进Dash的组件模板,做好属性和事件的映射即可。

内容的提问来源于stack exchange,提问作者Mth Clv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 13:54:25