Estoy creando este sitio y ahora mismo tengo 4 divs que hacen básicamente lo mismo, pero se copian y pegan 4 veces y se modifican 4 bits de información. ¿Hay alguna forma de usar reaccionar que pueda hacer que sea solo un div y una función maneje los diferentes parámetros necesarios para los divs? Aquí hay un ejemplo rápido.
ejemplorápido.jsx
import React, {useRef} from "react"; function test(props) { animalAmount = useRef(20); return ( <div> <div id='turtle-id'> <h1>I like turtles!</h1> <p>there are {animalAmount.current} turtles in my house!</p> <button>Click me!</button> </div> <div id='dog-id'> <h1>I like dogs!</h1> <p>there are {animalAmount.current} dogs in my house!</p> <button>Click me!</button> </div> <div id='fish-id'> <h1>I like fish!</h1> <p>there are {animalAmount.current} fish in my house!</p> <button>Click me!</button> </div> <div id='hippo-id'> <h1>I like hippos!</h1> <p>there are {animalAmount.current} hippos in my house!</p> <button>Click me!</button> </div> </div> ); } export default test;por razones específicas, no puedo simplemente crear un componente principal y llamarlo allí y duplicarlo cuatro veces, debe hacerse en este componente si es posible.
Cree una matriz con sus datos y luego use el map para imprimir los divs:
const data = [ { id: 'turtle-id', title: 'I like turtles', text: '...', // rest of needed data }, { // ... } ]; return ( data.map(item => { return ( <div key={item.id} id={item.id}> <h1>{item.title}</h1> <p>{item.text}</p> <button>Click me!</button> </div> ); }); );Puede crear una matriz de objetos fuera del componente y recorrerlos. Algo como esto.
const animals = [{ id: "turtle-id", title: "I like turtles!", defineText: (value) => `there are ${value} turtles in my house!` }, ....]y luego en la devolución de su componente, puede hacer algo como esto.
... return ( <div> {animals.map((animal) => { return ( <div key={animal.id} id={animal.id}> <h1>{animal.title}</h1> <p>{animal.defineText(animalAmount.current)}</p> <button>Click me!</button> </div> ); })} </div> ); ...Tenga un conjunto de datos que describan a los animales y establezca su estado con ellos.
Cambie sus contenedores de animales a un nuevo componente ( Animal ).
map sobre el estado de los animales para crear una serie de animales.
Cuando se hace clic en un botón, actualice el valor de conteo de ese animal.
const { useState } = React; // Pass in some data function Animals({ data }) { // Initialise state with the data const [ animals, setAnimals ] = useState(data); // Copy the state, find the name of the // animal we're updating the count for from // the container's dataset, find the index of the // animal object in state, update its count value // and the update the state function handleCount(e) { const copy = [...animals]; const { name } = e.target.closest('.animal').dataset; const index = copy.findIndex(obj => obj.name === name); ++copy[index].count; setAnimals(copy); } // `map` over the animals state // an return an array of Animal components return animals.map(animal => { return ( <Animal animal={animal} handleCount={handleCount} /> ); }); } // Animal component function Animal({ animal, handleCount }) { return ( <div className="animal" data-name={animal.name}> <h1>I like {animal.plural}!</h1> <p>There are {animal.count} {animal.plural} in my house!</p> <button onClick={handleCount}>Click me!</button> </div> ); } const data = [ { name: 'turtle', plural: 'turtles', count: 0 }, { name: 'dog', plural: 'dogs', count: 0 }, { name: 'fish', plural: 'fish', count: 0 }, { name: 'hippo', plural: 'hippos', count: 0 } ]; ReactDOM.render( <Animals data={data} />, document.getElementById('react') ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>