React项目中 “引入coze AI 应用开发平台“

前面我刚写了一种实现方式
是通过新建html文件,然后iframe渲染处理的解决方案
链接在这儿:https://blog.csdn.net/weixin_43517190/article/details/143369934?spm=1001.2014.3001.5501

接下来还有一种更简便的实现,现在分享给大家~ ❤️
在这里插入图片描述

在后台React项目中 我们往往都有一个index.html页面
在这个页面中,我们可以直接加以下代码

<script src="https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/0.1.0-beta.7/libs/cn/index.js"></script>
<script>
    window.CozeWebSDK = CozeWebSDK;
</script>

直接设置window.CozeWebSDK,
然后在要渲染的地方写以下代码

import React, { PureComponent } from 'react';
import { language } from '@comall-backend-builder/core/lib/services';
import './index.less';

export class AIHelper extends PureComponent<unknown, unknown> {

    componentDidMount() {
        // @ts-ignore
        new window.CozeWebSDK.WebChatClient({
            config: {
                bot_id: '',
            },
            componentProps: {
                title: '助手',
                lang: 'zh-CN',
                width: 460,
                layout: 'pc'
            },
            el: document.getElementById('ai-coze'),
        });
    }

    render() {
        return (
            <div className="ai-helper">
                <div className="ai-coze" id="ai-coze"></div>
            </div>
        );
    }
}



index.less

.ai-helper{
  position: fixed;
  right: 0px;
  bottom: 100px;
  z-index: 99999;
  .ai-coze{
    div{
      top: 0px;
      right: 0px;
      height: 100%;
    }
  }
}

----------------------------后续加更----------------------------
需求添加-进入页面默认打开助手:采用了id的click事件解决

import React, { PureComponent } from 'react';
import { language } from '@comall-backend-builder/core/lib/services';
import './index.less';

export class AIHelper extends PureComponent<unknown, unknown> {
    componentDidMount() {
        // @ts-ignore
        const cozeWebSDK = new window.CozeWebSDK.WebChatClient({
            config: {
                bot_id: '7408005351938801664',
            },
            componentProps: {
                title: language.getText('znkf'),
                lang: 'zh-CN',
                width: 460,
                layout: 'pc',
                icon: 'https://b-puzhehei-cdn.co-mall.net/global/magic-backend/ai-helper-new.gif',
            },
            el: document.getElementById('ai-coze'),
        });
        setTimeout(() => {
            cozeWebSDK?.options?.el?.children?.[1]?.click?.();
        }, 0);
    }

    render() {
        return (
            <div className="ai-helper">
                <div className="ai-coze" id="ai-coze"></div>
            </div>
        );
    }
}

更多推荐