【发布时间】:2021-10-10 00:46:27
【问题描述】:
我正在尝试将数据从 React.js 网络应用程序中的 HTML 表单发送到谷歌表格。
我已经在 index.html 中添加了脚本标签(在 <head> 和 <body> 中尝试过),但 gapi 仍然未定义。
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<div id="root"></div>
</body>
在组件中我这样做:
class Form extends React.Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
componentDidMount() {
this.handleClientLoad();
}
handleClientLoad = () => {
gapi.load("client:auth2", this.initClient);
};
updateSignInStatus() {}
initClient = () => {
gapi.client
.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
scope: SCOPE,
discoveryDocs: [
"https://sheets.googleapis.com/$discovery/rest?version=v4",
],
})
.then(() => {
gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSignInStatus);
this.updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
};
onFormSubmit(submissionValues) {
const params = {
spreadsheetId: SPREADSHEET_ID,
range: "Sheet1",
valueInputOption: "RAW",
insertDataOption: "INSERT_ROWS",
};
const valueRangeBody = {
majorDimension: "ROWS",
values: [submissionValues],
};
let request = gapi.client.sheets.spreadsheets.values.append(
params,
valueRangeBody
);
request.then(
function (response) {
console.log(response.result);
},
function (reason) {
console.error("error: " + reason.result.error.message);
}
);
}
render() {
return (
<form className="Form" onSubmit={this.onFormSubmit}>
...)};
}
我也尝试过window.gapi,但没有结果。
我知道在组件之前没有加载 gapi,但我不知道如何解决。
【问题讨论】:
标签: javascript html reactjs google-api-js-client