Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Pasar la entrada del usuario del componente funcional secundario al componente funcional principal

Estoy creando un generador de facturas donde el usuario puede agregar un artículo, su precio y la cantidad. Quiero acceder a las entradas del usuario como un estado desde un componente funcional secundario ( TableItems.js ) a un componente funcional principal ( TableSheet.js ) para poder guardar las entradas del usuario en una base de datos, preferiblemente en Firestore. Tengo problemas para acceder al valor de entrada del usuario desde el componente secundario al componente principal. He estado luchando con este error durante días, realmente espero que puedan ayudarme.

Este es el componente hijo

 import React, {useState, useEffect} from 'react' function TableItems({index, tableItem }) { const [price, setPrice] = useState(0); const [qty, setQty] = useState(0); const [total, setTotal] = useState([]); useEffect(() => { //arithmetically add price and qty values const x = Number(price) * Number(qty) setTotal(x) return () => { //clean up function will be here }; }, [price, qty, total ]); return ( <> <tr> <td><input type='text' required/></td> <td><input type='number' value={price} onChange={(e) => setPrice(e.target.value)}/></td> <td><input type='number' value={qty} onChange={(e) => setQty(e.target.value)}/></td> <td>{total}</td> </tr> </> ) } export default TableItems

Este es el componente principal

 import React, { useState } from 'react' import TableItems from './TableItems' function TableSheet() { const [tableItem, setTableItem] = useState([1]); //adding a new table cell (table row) const addCell = () => { setTableItem((t) => [...t, t + 1]) } return ( <div> <table> <thead> <th>Item Description</th> <th>Price</th> <th>Qty.</th> <th>Total</th> </thead> { tableItem.map((tableItem, index, setItem) => { return <TableItems key={index} tableItem={tableItem} setItem={setItem} addCell={addCell}/> }) } </table> <button onClick={addCell}>+</button> </div> ) } export default TableSheet
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Su estado tableItem debe contener objetos de artículo (cantidad y precio)

Elementos de tabla

 function TableItems({ index, tableItem, onChangeItem }) { return ( <> <tr> <td> <input type="text" required /> </td> <td> <input type="number" value={tableItem.price} onChange={(e) => onChangeItem(index, "price", e.target.value)} /> </td> <td> <input type="number" value={tableItem.quantity} onChange={(e) => onChangeItem(index, "quantity", e.target.value)} /> </td> <td>{Number(tableItem.price) * Number(tableItem.quantity)}</td> </tr> </> ); }

TablaHoja

 function TableSheet() { const [tableItem, setTableItem] = useState([ { price: 0, quantity: 0 } ]); const onChangeItem = (index, type, value) => { const newTable = tableItem.map((item, idx) => { if (idx === index) return { ...item, [type]: value }; return item; }); setTableItem(newTable); }; const addCell = () => { setTableItem((t) => [ ...t, { price: 0, quantity: 0 } ]); }; const totalPrice = tableItem.reduce((acc, cur) => { acc += Number(cur.price) * Number(cur.quantity); return acc; }, 0); return ( <div> <table> <thead> <th>Item Description</th> <th>Price</th> <th>Qty.</th> <th>Total</th> </thead> {tableItem.map((tableItem, index) => { return ( <TableItems key={index} index={index} tableItem={tableItem} onChangeItem={onChangeItem} /> ); })} </table> <button onClick={addCell}>+</button> <div>Total: {totalPrice}</div> </div> ); }

Puedes consultar en mi codeandbox . ¡Espero que ayude!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda