因此,来 self 熟悉的 PayPal 按钮的 Angular 背景,我无法让它为 React.js 工作。为有效的 react.js 构建 PayPal 按钮组件的方法是什么?有什么建议会有很大帮助吗?
最佳答案
有同样问题的 friend :这个简洁step-by-step guide可用于编写您自己的使用 PayPal REST API 的 React 组件。
在下面的代码片段中,注意:
- API 异步加载和
isScriptLoad*
Prop 检查加载状态 - showButton 保持状态(可以渲染也可以不渲染)
- 绑定(bind)到DOM
componentDidMount
对比componentWillReceiveProps
检查 API 的加载状态- 要传递给组件以管理交易的 Prop :total、currency、env、commit、client、onSuccess、onError、onCancel
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);
关于javascript - 在 React.js 中制作一个 Paypal 按钮来结帐项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482310/