【发布时间】:2022-07-12 18:00:47
【问题描述】:
我的表单在 react 中有这两个函数,第一个函数使用 react-hook-form 并从下面看到的输入字段中获取数据。
第二个下单购买,我只需要从“order.buyer = {}”中的第一个获取数据
进口
import { useCartContext } from './../../context/CartContext';
import { Button } from 'react-bootstrap'
import { v4 as uuidv4 } from 'uuid';
import { useForm } from 'react-hook-form';
功能
function Cart() {
const { cartList, emptyCart, deleteItem, sumaTotal } = useCartContext();
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data)
}
function generarOrden(data) {
let orden = {}
orden.buyer = (data);
orden.total = sumaTotal();
orden.date = new Date();
orden.items = cartList.map(cartItem => {
const id = cartItem.id
const nombre = cartItem.name
const precio = cartItem.price * cartItem.cantidad
return {id, nombre, precio}
})
console.log(orden);
}
购物车部分 + 带输入的表单
return (
<>
<div className='tables'>
<table>
<thead>
<tr>
<th>Imagen</th>
<th>Nombre</th>
<th>Categoria</th>
<th>Descripcion</th>
<th>Cantidad</th>
<th>Precio</th>
<th>Total</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
{cartList.map(prod =>
<tr key={uuidv4()}>
<td><img src={prod.imgSource} alt="foto" className='img-cart'/> </td>
<td>{prod.name} </td>
<td>Games</td>
<td>{prod.desc} </td>
<td>{prod.cantidad} </td>
<td>${prod.price} </td>
<td>${prod.price * prod.cantidad} </td>
<td><Button className='button-card' onClick={()=>deleteItem(prod.id)}>Quitar Item</Button></td>
</tr>
)}
</tbody>
</table>
</div>
<div>
<h4 className='cart-orden space'> Total de la compra: ${sumaTotal()} </h4>
<Button onClick={emptyCart} className="button-card space">Empty Cart</Button>
<Button onClick={generarOrden} className="button-card space">Generar Orden</Button>
<form className='container-fluid bg-dark' onSubmit={handleSubmit(onSubmit)}>
<div className="mb-3">
<label className="form-label">Name</label>
<input type="text" className="form-control" placeholder='Alejandro Otero' name='name' {...register('name', { required: true })}/>
</div>
<div className="mb-3">
<label className="form-label">Email</label>
<input type="email" className="form-control" placeholder='Example@gmail.com' name='email' {...register('email', { required: true })}/>
</div>
<div className="mb-3">
<label className="form-label">Phone Number</label>
<input type="number" className="form-control" placeholder='11-4058-8867' name='phone' {...register('phone', { required: true })}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</>
)
}
export default Cart
是一个简单的“问题”,但我是一个使用 react/js 的完整菜鸟,所以我找不到将数据从 onSubmit 提供给generarOrden 的方法
【问题讨论】:
-
什么不起作用?
-
一切正常,但我需要从“onSubmit()”函数中获取数据到 order.buyer {},我是 react/js 的菜鸟,所以我遇到了麻烦。
-
order.buyer = 数据
-
那不行,order.buyer 返回“SyntheticBaseEvent”
-
你能展示整个组件吗?
标签: reactjs forms react-hook-form