首页 > 解决方案 > 如何在 react js 中使用脚本标签元素,我正在使用 react 钩子

问题描述

PayPal使用智能支付按钮:

如何使用 Paypal 中的智能支付按钮?当我渲染按钮时出现错误,这是我想在这里使用的脚本:

https://developer.paypal.com/demo/checkout/#/pattern/client

我正在使用 useEffect 加载脚本:

useEffect(() => {
    const script = document.createElement('script');

    script.src = "https://www.paypal.com/sdk/js?client-id=API_KEY&currency=USD";
    script.async = true;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, []);

之后,我正在渲染卡中的注册摘要,我想在其中渲染此 Paypal 智能按钮

<Card className={classes.card}>
        <CardContent style={{textAlign:"center"}}>
            .....
            //registration details
            .....
        </CardContent>
        <CardActions style={{justifyContent:"center"}} >
            {renderPaypal}
         // renderPaypal invokes the function to render the button
        </CardActions>

    </Card>

这是我渲染按钮的功能:

   const renderPaypal=()=>{
    return (
        <script>
    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({

        // Set up the transaction
        createOrder: function(data, actions) {
            return fetch('/demo/checkout/api/paypal/order/create/', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(data) {
                return data.orderID;
            });
        },

        // Finalize the transaction
        onApprove: function(data, actions) {
            return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(details) {
                // Show a success message to the buyer
                alert('Transaction completed by ' + details.payer.name.given_name + '!');
            });
        }


    }).render('#paypal-button-container');
</script>

)
}

标签: javascriptreactjsreact-hooks

解决方案


推荐阅读