我在试着做我认为很简单的事情。在提交由GravityForm组件拉入的表单时,我将handleSubmit状态设置为true,然后呈现感谢消息(这一切都很好,我已经删除了URL,但我可以向您保证这一点是正确的)。
当我加载成功消息时,我的问题就出现了。setTimeout函数显示id。有没有一种方法可以停止它显示该id,或者以不同的方式实现这个函数,这意味着它不会显示?
预期的功能是,感谢消息将显示3秒,然后页面将加载到不同的网站。
import "./form.css";
import React, { Component } from "react";
import GravityForm from "react-gravity-form";
import styled from "styled-components";
export class Gravity extends Component {
state = {
handleSubmit : false,
}
successMessage = styled.div`
display: block;
color: #fff;
font-size: 24px;
text-align: center;
`;
render() {
const { handleSubmit } = this.state;
if (!handleSubmit) {
return (
<GravityForm
backendUrl="https://removedurlforclientprivacy.com/wp-json/glamrock/v1/gf/forms"
formID="3"
onSubmitSuccess={ () => {
this.setState({
handleSubmit : true,
})
} }
/>
);
} else {
return (
<>
<this.successMessage>
<p>Thanks for entering our competition!<br />If you're our lucky winner, we will let you know.</p>
</this.successMessage>
{ setTimeout(() => window.location.href = 'https://google.co.uk', 3000) }
</>
)
}
}
}
export default Gravity
发布于 2021-10-28 03:40:50
您看到id的原因是因为setTimeout函数返回id。想象一下,setTimeout()调用被简单地替换为123,这样它看起来就像{ 123 },它当然会显示123的值。
隐藏该值的一种方法是将其转换为要计算的表达式-类似于{ 123 && <> },这样将返回空元素,而不是值本身(显然将123替换为您的setTimeout()函数,如下所示:
{ setTimeout(() => window.location.href = 'https://google.co.uk', 3000) && <></> }
您还可以使用{ 123 && undefined }或{ 123 && null },这很可能导致根本不返回元素,再次确保用setTimeout()函数替换123。
发布于 2021-10-28 03:34:15
您是否可以尝试这种方式,创建一个函数,您可以设置您的成功的东西,并在您的else条件下调用它
renderSuccesssMessage = () => {
setTimeout(() => window.location.href = 'https://google.co.uk', 3000)
return (
<this.successMessage>
<p>Thanks for entering our competition!<br />If you're our lucky winner, we will let you know.</p>
</this.successMessage>
)
}
并将此函数调用到else条件中
else {
return (
this.renderSuccessMessage()
)
}
发布于 2021-10-28 03:31:28
您可以像下面这样更改您的onSubmitSuccess函数,并从else块中删除setTimeout:
onSubmitSuccess={() => {
this.setState({
handleSubmit : true,
},() => {
setTimeout(() => window.location.href = 'https://google.co.uk', 3000)
});
}}
https://stackoverflow.com/questions/69753194
复制