如何在 React 中导入带有数据属性的脚本标签?
How to import script tag with data attribute in React?
我想在 React 中导入 Razorpay 按钮,以便我可以接受付款。但是它没有显示在我的组件中。
Razorpay 按钮代码:-
<form>
<script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_G8bIDza4zHQRfm">
</script>
</form>
我已经尝试过这样做但失败了:-
import React, { useEffect } from 'react';
import './Homepage.css';
const Homepage = () => {
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/payment-button.js';
script['data-payment_button_id'] = 'pl_G8bIDza4zHQRfm';
script.async = true;
const element = document.querySelector('#home form');
element.appendChild(script);
return () => {
element.removeChild(script);
};
}, []);
return (
<section id='home'>
<form></form>
</section>
);
};
export default Homepage;
文档参考:- https://razorpay.com/docs/payment-button/donations/#step-3-embed-payment-button-code-in-website
如果你想设置 data-attribute
你可以使用 Element.setAttribute():
script.setAttribute('data-payment_button_id', 'pl_G8bIDza4zHQRfm');
我建议您使用 useRef
挂钩并获取表单参考:
const form = useRef(null);
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/payment-button.js';
script.setAttribute('data-payment_button_id', 'pl_G8bIDza4zHQRfm');
script.async = true;
form.current.appendChild(script);
return () => {
form.current.removeChild(script);
};
}, []);
return (
<section id='home'>
<form ref={form}></form>
</section>
);
我想在 React 中导入 Razorpay 按钮,以便我可以接受付款。但是它没有显示在我的组件中。
Razorpay 按钮代码:-
<form>
<script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_G8bIDza4zHQRfm">
</script>
</form>
我已经尝试过这样做但失败了:-
import React, { useEffect } from 'react';
import './Homepage.css';
const Homepage = () => {
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/payment-button.js';
script['data-payment_button_id'] = 'pl_G8bIDza4zHQRfm';
script.async = true;
const element = document.querySelector('#home form');
element.appendChild(script);
return () => {
element.removeChild(script);
};
}, []);
return (
<section id='home'>
<form></form>
</section>
);
};
export default Homepage;
文档参考:- https://razorpay.com/docs/payment-button/donations/#step-3-embed-payment-button-code-in-website
如果你想设置 data-attribute
你可以使用 Element.setAttribute():
script.setAttribute('data-payment_button_id', 'pl_G8bIDza4zHQRfm');
我建议您使用 useRef
挂钩并获取表单参考:
const form = useRef(null);
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://checkout.razorpay.com/v1/payment-button.js';
script.setAttribute('data-payment_button_id', 'pl_G8bIDza4zHQRfm');
script.async = true;
form.current.appendChild(script);
return () => {
form.current.removeChild(script);
};
}, []);
return (
<section id='home'>
<form ref={form}></form>
</section>
);