我是React和Formik的新手,请帮我解决这个问题,我想使用.onSave{product}
将输入的值传递给另一个组件:
import { Formik } from 'formik';
import * as Yup from 'yup';
export default class ProductForm extends React.Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event){
event.preventDefault();
var product = {};
product.productName = this.refs.productName.value;
product.quantity = this.refs.quantity.value;
product.price = this.refs.price.value;
this.props.onSave(product);
}
render() {
return (
<Formik initialValues={{productName:"",quantity:"",price:""}} validation`enter code here`Schema={Yup.object().shape({productName:Yup.string().required("Product Name is required"),quantity:Yup.number().required("Quantity is required").positive().integer(),price:Yup.number().required("Quantity is required").positive().integer()}>
{props=>{
const{
values,
touched,
errors,
handleChange,
handleBlur
}=props;
return(<div>
<h1>Add Product</h1>
<form autoComplete='off' onSubmit={this.onSubmit}>
<input type="text" onChange={handleChange} onBlur={handleBlur} name="productName" value={values.productName} placeholder="Enter Product Name"/>
{
errors.productName && touched.productName &&(
<div className="errorName" >{errors.productName}</div>
)
}<br></br><br></br>
<input type="text" onChange={handleChange} onBlur={handleBlur} name="quantity" value={values.quantity} placeholder="Enter Quantity"/>
{
errors.quantity && touched.quantity &&(
<div className="errorName">{errors.quantity}</div>
)
}<br></br><br></br>
<input type="text" onChange={handleChange} onBlur={handleBlur} name="price" value={values.price} placeholder="Enter Price"/>
{
errors.price&&touched.price&&(
<div className="errorName">{errors.price}</div>
)
}<br></br><br></br>
<button type="submit" >Submit</button>
</form> </div>
)
}
}
</Formik>
);
}
}
答案 0 :(得分:0)
尝试这样
hemisphere = false
//初始化
this.inputRef = React.createRef();
//保存对DOM节点的引用
this.myInput.current
答案 1 :(得分:0)
您需要考虑的几件事:
您必须将提交处理程序绑定到formik,然后在 form
上使用它<Formik
initialValues={{ productName: "", quantity: "", price: "" }}
validationSchema={Yup.object().shape({
productName: Yup.string().required("Product Name is required"),
quantity: Yup.number()
.required("Quantity is required")
.positive()
.integer(),
price: Yup.number()
.required("Quantity is required")
.positive()
.integer()
})}
onSubmit={this.onSubmit}
>
{({
values,
touched,
errors,
handleSubmit,
handleChange,
handleBlur
}) => {
return (
<div>
<h1>Add Product</h1>
<form autoComplete="off" onSubmit={handleSubmit}>
....
</form>
</div>
)
);
}}
</Formik>
对于事件处理程序的提交也有一些更改:
onSubmit(formData) {
var product = {};
product.productName = formData.productName;
product.quantity = formData.quantity;
product.price = formData.price;
console.log(product);
this.props.onSave(product);
}
请检查code