Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Reaccionar agregar clase a un elemento de la lista después de hacer clic en el botón

Estoy representando alrededor de 100 elementos de lista como en el código a continuación. Cuando hago clic en el botón, quiero mostrar texto solo para ese elemento en el que hice clic, pero muestra texto en todos.

Otra cosa importante es que necesito este botón solo en teléfonos

Lo sé, hay otra forma de usar el estado de reacción, pero necesito usar className.

Gracias a todos

 const listItem = () => { let showMore = false; <div> <div className={`text ${showMore ? "active" : ""}`}> blablabla</div> </div> <button onClick={() => (showMore = !showMore)}>Show more</button> } <List> <listItem /> </List>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Para alternar className sin usar el estado, puede usar ref . Aquí hay un ejemplo:

 const ListItem = () => { const ref = React.createRef(); return ( <React.Fragment> <div> <div ref={ref} className={`text`}> blablabla </div> </div> <button onClick={() => ref.current.classList.toggle('active')}> Show more </button> </React.Fragment> ); }; function App(){ return ( <React.Fragment> <ListItem/> <ListItem/> <ListItem/> </React.Fragment> ); } ReactDOM.render(<App/>, document.getElementById('root'))
 .text{ color: red; display: none; } .text.active{ display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

about 4 years ago · Juan Pablo Isaza Report

0

Deberías usar useState en este caso

Demo en vivo

Demostración de Codesandbox

 const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> <div> <div className={`text ${showMore ? "active" : ""}`}>{text}</div> </div> <button onClick={() => setShowMore((s) => !s)}>Show more</button> </div> ); };
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!