• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

146
Views
¿Cómo pasar el valor principal al secundario en el primer renderizado y cambiar el valor del componente principal del secundario?

Entonces, lo que estoy tratando de hacer es pasar un número al componente secundario, que solo se pasará en el primer renderizado. Después de eso, estoy tratando de cambiar el valor actual y pasar el valor del elemento secundario al componente principal. Sin embargo, no puedo pasar el precio al niño, ya que estoy recibiendo undefined .

No estoy seguro de cómo puedo pasar los datos en este contexto, ¿alguna idea?

 function Parent(props, {price}) { const [amount, setAmount] = React.useState("200"); function handleChange (newValue) { setValue(newValue); } // We pass a callback to Child return <Child price={amount} value={value} onChange={handleChange} />; } function Child (props, {price}) { const [amount, setAmount] = React.useState(""); function handleChange(event) { setAmount(event.target.value) // Here, we invoke the callback with the new value props.onChange(event.target.value); } useEffect(() => { setAmount(price) //Pass value from parent if it has one }, []) return <input value={props.value} onChange={handleChange} /> }
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Para este caso de uso, solo necesita pasar un valor del componente principal a su componente secundario. Está duplicando valores de una manera que es innecesaria y genera confusión. Utilice la variable de estado amount o value , no ambas.

Para arreglar esto:

  • Use solo la variable de estado de amount tanto en <Parent/> como en <Child/> .
  • Cambie la llamada setValue() a setAmount() en la función handleChange() .
  • Elimina la propiedad de value que se pasa a <Child/> .
  • Elimine el valor desestructurado {price} de <Child/> y acceda a la amount en el gancho useEffect() en su lugar a través de la propiedad de value .

Además:

  • No use props y sintaxis {propVariable} al mismo tiempo en la lista de parámetros de un componente. Use cualquiera de los dos, no ambos.

Componente principal:

 function Parent(props) { const [amount, setAmount] = useState("200"); function handleChange(newValue) { setAmount(newValue); // You can use this to test that the child component is triggering // the handleChange() function prop passed to it. console.log(newValue); } // We pass a callback to Child return <Child value={amount} onChange={handleChange} />; }

Componente hijo:

 function Child(props) { const [amount, setAmount] = useState(""); function handleChange(event) { setAmount(event.target.value); // Here, we invoke the callback with the new value props.onChange(event.target.value); } useEffect(() => { setAmount(props.value); //Pass value from parent if it has one }, []); return <input value={props.value} onChange={handleChange} />; }

Sin embargo, incluso todo lo anterior dentro de <Child/> no es necesario. Solo necesita los props en el componente secundario, y no necesita mantener el estado interno de acuerdo con las mejores prácticas, es decir, tener una única fuente de verdad y controlar el estado solo en el elemento principal, por lo que puede modificar <Child/> más para:

 function Child(props) { function handleChange(event) { // Here, we invoke the callback with the new value props.onChange(event.target.value); } return <input value={props.value} onChange={handleChange} />; }
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error