gpt4 book ai didi

javascript - 如何在提交时重置输入表单(ReactJS)

转载 作者:太空宇宙 更新时间:2023-11-04 15:25:48 25 4
gpt4 key购买 nike

我在提交时重置输入表单时遇到一些困难。我希望在表单提交成功后将输入字段重置为空白值,但目前我也同意它一般只是重置 onSubmit ,这两个我都没有做过到目前为止能够弄清楚。具体来说,我尝试的是:

 class SubscribeForm extends React.Component {
constructor(props, ...args) {
super(props, ...args)
this.state = {
status: null,
msg: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event.preventDefault();
this.setState({ value: '' });
}

使用表单布局:

<form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>

<input
ref={node => (this.input = node)}
type="email"
defaultValue=""
name="EMAIL"
required={true}
placeholder={messages.inputPlaceholder}
/>
<button
disabled={this.state.status === "sending" || this.state.status === "success"}
onClick={this.onSubmit}
type="submit"
className="btn-group"
id="AlertButton"
>
<p>Sign Up</p>
</button>
</form>

但是,当实际单击按钮时,在表单的 onSubmit 属性中调用 {this.handleSumbit} 似乎没有任何结果。我在这里缺少什么明显的东西还是这是一个更复杂的问题?

下面提供的是完整的相关代码片段:

class SubscribeForm extends React.Component {
constructor(props, ...args) {
super(props, ...args)
this.state = {
status: null,
msg: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
event.preventDefault();
this.setState({ value: '' });
}

onSubmit = e => {
e.preventDefault()
if (!this.input.value || this.input.value.length < 5 || this.input.value.indexOf("@") === -1) {
this.setState({
status: "error"
})
return
}
const url = getAjaxUrl(this.props.action) + `&EMAIL=${encodeURIComponent(this.input.value)}`;
this.setState(
{
status: "sending",
msg: null
}, () => jsonp(url, {
param: "c"
}, (err, data) => {
if (err) {
this.setState({
status: 'error',
msg: err
})
} else if (data.result !== 'success') {
this.setState({
status: 'error',
msg: data.msg,
})

} else {
this.input.defaultValue = "";
this.setState({
status: 'success',
msg: data.msg,
inputPlaceholder: "E-mail"
})
}
})
)
}
render() {
const { action, messages, className, style, styles } = this.props
const { status, msg } = this.state
return (
<div className={className} style={style}>
<form onSubmit={this.handleSubmit} action={action} method="post" id="alert-form" noValidate>

<input
ref={node => (this.input = node)}
type="email"
defaultValue=""
name="EMAIL"
required={true}
placeholder={messages.inputPlaceholder}
/>
<button
disabled={this.state.status === "sending" || this.state.status === "success"}
onClick={this.onSubmit}
type="submit"
className="btn-group"
id="AlertButton"
>
<p>Sign Up</p>
</button>
</form>

</div>
)
}
}

最佳答案

试试这个

handleSubmit(event) {
event.preventDefault();
this.input.value = '';
this.setState({ value: '' });
}

https://codepen.io/va0000ll/pen/zRXNwY

关于javascript - 如何在提交时重置输入表单(ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49080396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com