我已经在我的react组件中使用了calendly API
我尝试使用以下代码:
import React, { Component } from 'react'
import FullScreenModal from '../../../UIComponents/FullScreenModal'
export default class MeetingBooking extends Component {
state={
isLoading: false
}
componentDidMount() {
console.log(this.state.isLoading)
const head = document.querySelector('head');
const script = document.createElement('script');
script.setAttribute('src', 'https://assets.calendly.com/assets/external/widget.js');
head.appendChild(script);
this.setState({loading: false})
}
render() {
console.log(this.state.isLoading)
return (
<FullScreenModal open={this.props.open} title={"Book a Meeting"} handleClose={this.props.handleClose}>
{this.state.isLoading ?
<p>Loading...!!!!</p> :
<div
className="calendly-inline-widget"
data-url="https://calendly.com/kristofferlocktolboll"
style={{minWidth: '320px', height: '580px'}}>
</div>
}
</FullScreenModal>
)
}
}
问题在于,我无法像使用Axios
或fetch API
请求那样,等待来自URL的请求,因此无论何时插入脚本,加载组件都不会如图所示。
所以我正在寻找一种方法来监听注入的javascript并等待它,因此我可以同时展示我的<p>Loading....!!!!</p>
,这可以实现吗?
答案 0 :(得分:2)
您可以向load
元素添加<script>
事件侦听器,下面是一个示例:
export default class MeetingBooking extends Component {
state = {
isLoading: false
}
componentDidMount() {
this.setState({ isLoading: true }, () => {
const script = document.createElement('script');
script.type = 'text/javascript';
script.onload = () => this.setState({ isLoading: false });
script.src = 'https://assets.calendly.com/assets/external/widget.js';
document.head.appendChild(script);
});
}
}
答案 1 :(得分:0)
import React, { Component } from 'react'
import FullScreenModal from '../../../UIComponents/FullScreenModal'
export default class MeetingBooking extends Component {
state={
isLoading: true
}
async componentDidMount() {
if (this.state.isLoading) {
const head = document.querySelector('head');
const script = document.createElement("script");
script.src = 'https://assets.calendly.com/assets/external/widget.js';
script.async = true;
head.appendChild(script);
await this.setState({loading: false})
}
}
render() {
console.log(this.state.isLoading)
return (
<FullScreenModal open={this.props.open} title={"Book a Meeting"} handleClose={this.props.handleClose}>
{this.state.isLoading ?
<p>Loading...!!!!</p> :
<div
className="calendly-inline-widget"
data-url="https://calendly.com/kristofferlocktolboll"
style={{minWidth: '320px', height: '580px'}}>
</div>
}
</FullScreenModal>
)
}
}