比如我在直播间添加了一个按钮,通过点击这个按钮,弹出来一个弹窗,这个使用的就是React语法和antdui实现的。具体实现的步骤就和你写React一样简单。
在页面插入抢购按钮
在页面中插入元素的方式有很多种,可以看官方文档:Life Cycle of Plasmo CSUI – Plasmo,其中最常用的就是两个,一个是在页面中指定元素的位置后面紧跟着插入元素,另外一个就是在指定元素的上面插入元素,这都是通过配置PlasmoGetInlineAnchor和PlasmoGetOverlayAnchorList来实现的。
实现弹窗功能
这个就需要一些操作了,第一个需要先引入antd的样式,然后在tsx中使用useState来实现控制,并渲染弹窗元素。引入样式需要使用getStyle方法。所有代码如下:
import type {
PlasmoCSConfig,
PlasmoGetInlineAnchor,
PlasmoGetOverlayAnchorList,
} from 'plasmo'
import { Storage } from '@plasmohq/storage'
import antdResetCssText from 'data-text:antd/dist/reset.css'
import cssText from 'data-text:~/contents/index.scss'
import { Button, Modal } from 'antd'
import { useState } from 'react'
export const config: PlasmoCSConfig = {
matches: ['https://live.douyin.com/*'],
}
// 初始化仓库存储
const storage = new Storage({
area: 'local',
})
// load style file
export const getStyle = () => {
const style = document.createElement('style')
style.textContent = antdResetCssText + cssText
return style
}
// insert into page dom,紧挨着后面
export const getInlineAnchor: PlasmoGetInlineAnchor = () =>
document.querySelector(`div.cjeyI4Ky > div > div.khbqOfnm`)
// 覆盖到元素上
// export const getOverlayAnchorList: PlasmoGetOverlayAnchorList = async () =>
// document.querySelectorAll('div.RQFWObp0 > div > div:nth-child(1) > div')
const CustomButton = () => {
const [isModalOpen, setIsModalOpen] = useState(false)
const showModal = () => {
setIsModalOpen(true)
}
const handleOk = () => {
setIsModalOpen(false)
}
const handleCancel = () => {
setIsModalOpen(false)
}
return (
<div>
<div className="controlBtn" onClick={showModal}>
抢购
</div>
<Modal
title="Basic Modal"
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
</div>
)
}
export default CustomButton