所以来自我熟悉的PayPal按钮的角度背景,我无法让它为React.js工作。为react.js构建PayPal按钮组件的方法是什么?任何建议都会有很大帮助吗?
答案 0 :(得分:0)
任何有同样问题的人:这个简洁的step-by-step guide可以用来编写你自己的使用PayPal REST API的React组件。
在下面的代码片段中,请注意:
isScriptLoad*
道具以检查加载状态componentDidMount
vs componentWillReceiveProps
检查API的加载状态payment
和authorize
方法
import React from 'react';
import ReactDOM from 'react-dom';
import scriptLoader from 'react-async-script-loader';
class PaypalButton extends React.Component {
constructor(props) {
super(props);
this.state = {
showButton: false,
};
window.React = React;
window.ReactDOM = ReactDOM;
}
componentDidMount() {
const {
isScriptLoaded,
isScriptLoadSucceed
} = this.props;
if (isScriptLoaded && isScriptLoadSucceed) {
this.setState({ showButton: true });
}
}
componentWillReceiveProps(nextProps) {
const {
isScriptLoaded,
isScriptLoadSucceed,
} = nextProps;
const isLoadedButWasntLoadedBefore =
!this.state.showButton &&
!this.props.isScriptLoaded &&
isScriptLoaded;
if (isLoadedButWasntLoadedBefore) {
if (isScriptLoadSucceed) {
this.setState({ showButton: true });
}
}
}
render() {
const {
total,
currency,
env,
commit,
client,
onSuccess,
onError,
onCancel,
} = this.props;
const {
showButton,
} = this.state;
const payment = () =>
paypal.rest.payment.create(env, client, {
transactions: [
{
amount: {
total,
currency,
}
},
],
});
const onAuthorize = (data, actions) =>
actions.payment.execute()
.then(() => {
const payment = {
paid: true,
cancelled: false,
payerID: data.payerID,
paymentID: data.paymentID,
paymentToken: data.paymentToken,
returnUrl: data.returnUrl,
};
onSuccess(payment);
});
return (
<div>
{showButton && <paypal.Button.react
env={env}
client={client}
commit={commit}
payment={payment}
onAuthorize={onAuthorize}
onCancel={onCancel}
onError={onError}
/>}
</div>
);
}
}
export default scriptLoader('https://www.paypalobjects.com/api/checkout.js')(PaypalButton);
&#13;