能否请您告诉我为什么单击按钮刷新页面会做出反应?我在输入字段中输入内容,然后按按钮,页面刷新 我想获取表单字段的值 https://codesandbox.io/s/green-frost-414qi
class ContactForm extends React.Component {
handleSubmit = values => {
// print the form values to the console
console.log(values);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
}
}
const ContactRForm = reduxForm({
// a unique name for the form
form: "contact"
})(ContactForm);
export default ContactRForm;
答案 0 :(得分:4)
表单是提交事件后刷新页面的标准行为。要停止此操作,您可以添加event.preventDefault()
handleSubmit = event => {
event.preventDefault()
console.log(event.target.firstName.value); //get value from input with name of firstName
};
对于Redux-Forms,为了获取values
对象并且不刷新页面,我们必须使用Redux-form为我们创建的事件处理程序。它是在我们将onSubmit道具传递给Form组件时创建的:
<ContactRForm onSubmit={this.submit} />
有趣的是,该处理程序现在可以通过道具handleSubmit()
来使用,我希望它可以内置event.preventDefault()
。
尝试将其添加到您的表单组件代码中:
import React from "react";
import { Field, reduxForm } from "redux-form";
class ContactForm extends React.Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
<label htmlFor="lastname">Last Name</label>
<Field name="lastname" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
}
}
const ContactRForm = reduxForm({
// a unique name for the form
form: "contact"
})(ContactForm);
export default ContactRForm;
现在,将发生与原始submit
函数相同的功能,并且页面不会刷新。 :)
答案 1 :(得分:0)
您可以使用以下更改来实现此目的。
class ContactForm extends React.Component {
constructor(props){
super(props);
this.state = {
fieldValue : ''
}
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateInput(event){
this.setState({username : event.target.value})
}
handleSubmit = event=> {
// print the form values to the console
event.preventDefault() // this is used to prevent the form submission
console.log('Your input value is: ' + this.state.username) // your input field value
};
render() {
return (
<form>
<div>
<label htmlFor="firstName">First Name</label>
<Field value={input} onChange={this.updateInput} /> // set the input value
</div>
<button type="submit" onClick={this.handleSubmit} >Submit</button>
</form>
);
}
}
const ContactRForm = reduxForm({
// a unique name for the form
form: "contact"
})(ContactForm);
export default ContactRForm;
答案 2 :(得分:0)
这是HTML表单在提交按钮上刷新页面的默认行为。您可以通过添加 event.preventDefault();
来停止刷新有关更多详细信息,您可以阅读ReactJS Form documentation
handleSubmit = e => {
event.preventDefault()
// get form value by accessing target values
console.log(e.target.firstName.value);
};