我有一个 react 应用程序,它使用 Plotly.js 在前端动态生成图像.我想添加图像共享功能。我正在尝试使用 react-share为了这。社交平台需要图片 URL 进行图片分享,不支持 base64 编码等格式的图片。后端被实现,因此它可以接收base64格式的图像,存储在数据库中并返回图像的URL,然后用于与react-share
共享.
由于图像是动态生成的(例如,每次用户调整图表大小时它都会改变),所以当用户单击共享图标时,一切都应该完成。
所以用户点击分享图标后,前端生成的图片应该保存到后端
let imgURI;
const handleClick = () => {
Plotly.toImage('chartContainer', {
format: 'png',
width: 1000,
height: 600
})
.then(dataUrl => api.post('/image/base64ToPng', { image: dataUrl })
.then(
(response) => {
imgURI = response.data.imgURI;
},
failure => console.error(failure)
));
};
收到响应后,像这样传递给共享组件<FacebookShareButton
url={imgURI}
>
<FacebookIcon/>
</FacebookShareButton>
代码示例不是异步的,所以图片 URI 没有传递给共享组件,因此共享不起作用。我尝试使用条件传递 Prop ,具体取决于它是否已定义并且没有提出解决方案。我也查了some issues in react-share repo处理异步网址,但似乎没有一个处理点击时的动态图像共享。我非常感谢有关如何完成此任务的提示。
最佳答案
这是一个严重的黑客领域,如果this PR,整个事情会简单得多。已经完成。
但是,下面的代码应该可以工作(见 codesandbox)。
关键步骤是:
openShareDialogOnClick
= false
)onClick
facebook 按钮的处理程序,该按钮异步获取 url 并设置状态(触发重新渲染)url
属性中具有真实地址),然后将 url 重新设置为“none "import { useEffect, useRef, useState } from "react";
import { FacebookIcon, FacebookShareButton } from "react-share";
async function getUrFromService(): Promise<string> {
// The real implementation would make a network call here.
await new Promise((resolve) => setTimeout(resolve, 1000));
return "https://via.placeholder.com/150";
}
export default function App() {
const shareButton = useRef<HTMLButtonElement>(null);
const [url, setUrl] = useState<string>("none"); // Unfortunately, we have to have a dummy string here, or FacebookShareButton will blow up.
// Provide an onClick handler that asyncronously fetches the url and sets it in the state.
const onClick = async () => {
// Be sure to check for the "none" state, so we don't trigger an infinite loop.
if (url === "none") {
const newUrl = await getUrFromService();
setUrl(newUrl);
}
};
// Whenever "url" changes and we re-render, we manually fire the click event on the button, and then re-set the url.
useEffect(() => {
if (url !== "none") {
shareButton.current?.click();
setUrl("none");
}
}, [url, shareButton]);
return (
<FacebookShareButton
ref={shareButton}
// Disable calling the dialog if we don't have a url yet.
openShareDialogOnClick={url !== "none"}
url={url}
onClick={onClick}
>
<FacebookIcon />
</FacebookShareButton>
);
}
关于javascript - 如何通过 react-share 共享动态生成的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69996381/