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

435
Visualizações
Cambiar el texto del botón en bucle usando React

¿Es posible cambiar el texto del botón que se crea usando array. Si es posible, ¿qué debo hacer con la función onClick en el botón? Aquí está el código de ejemplo :

 function RenderFeeds(props) { const list = [] props.products.forEach((product) => { list.push( <> <h1>{product.name}</h1> <h2>{product.company_name}</h2> <h2>{product.description}</h2> <button onClick={}>{product.watchlist==false ? 'Add to watchlist':'Remove From watchlist'}</button> </> ) }) return ( <> {list} </> )}

Básicamente, tengo una matriz que contiene este valor:

 [{ "name": "lorem ipsum", "description": "Nam vel nisi rutrum quam ", "company_name": "PT dapibus ", "company_slug": "pt-dapibus", "watchlist": true, "id": 1 }]

Estoy creando el componente usando esta matriz. La variable de la lista de observación afectará el texto del botón. Si es cierto , quiero que el botón tenga Eliminar de la lista de observación y viceversa.

Soy consciente de que podemos usar gancho en React y aplicar useState para la función del botón onClick . Pero no sé cómo inicializo el estado si uso loop para crear el componente.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

En el siguiente fragmento, implementé un ejemplo, solo para simplificar, usé datos estáticos como lista. Espero que pueda ayudar.

 const data = [{ "name": "lorem ipsum", "description": "description1", "company_name": "PT dapibus ", "company_slug": "pt-dapibus", "watchlist": true, "id": 1 },{ "name": "lorem ipsum2", "description": "description2", "company_name": "Google", "company_slug": "company_slug", "watchlist": true, "id": 2 }] function RenderFeeds({ feeds, onAddToWatch, onRemoveFromWatch }) { return ( <React.Fragment>{/* or any markup you want */} {feeds.map((feed) => ( <div className="feed" key={feed.id}> <h1>{feed.name}</h1> <h2>{feed.company_name}</h2> <h2>{feed.description}</h2> <button onClick={() => feed.watchlist ? onRemoveFromWatch(feed.id) : onAddToWatch(feed.id) } > {feed.watchlist ? 'Remove From watchlist' : 'Add to watchlist'} </button> </div> ))} </React.Fragment> ); } function Feed() { const [feeds, setFeeds] = React.useState([]); React.useEffect(() => { //receiving data, for example fetching data by ajax or whatever setFeeds(data); }, []); const handleAddToWatch = (id) => { // implement updating feeds, for example making an ajax request and getting new data setFeeds((feeds) => feeds.map((feed) => ({ ...feed, watchlist: feed.id == id ? true : feed.watchlist, })) ); }; const handleRemoveFromWatch = (id) => { // implement updating feeds, for example making an ajax request and getting new data setFeeds(feeds => feeds.map((feed) => ({ ...feed, watchlist: feed.id == id ? false : feed.watchlist, })) ); }; return ( <RenderFeeds feeds={feeds} onAddToWatch={handleAddToWatch} onRemoveFromWatch={handleRemoveFromWatch} /> ); } ReactDOM.render(<Feed/>, document.getElementById('root'))
 .feed{ border: 2px solid #ccc; padding: 15px; margin: 15px; } .feed h1{ margin: 0}
 <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="root"></div>

about 4 years ago · Santiago Trujillo Relatório

0

Si está renderizando cosas basadas en accesorios, no es realmente necesario usar ganchos en este caso.

Algo como esto debería funcionar:

 function RenderFeeds(props) { return ( <> {props.products.map((product) => { return ( <> <h1>{product.name}</h1> <h2>{product.company_name}</h2> <h2>{product.description}</h2> <button onClick={}>{product.watchlist==false ? 'Add to watchlist':'Remove From watchlist'}</button> </> ) })} </> )}
about 4 years ago · Santiago Trujillo Relatório

0

No es necesario crear una list de variables adicional y recorrer la lista de productos que obtiene como accesorios y luego empujarla a la list y luego renderizar la list ; en su lugar, puede recorrer directamente la lista de productos usando el map . ¡Y no hay necesidad de verificar product.watchlist==false cuando puede usar ! NO lógico

 function RenderFeeds(props) { return ( <> {props.products.map((product) => { return ( <> <h1>{product.name}</h1> <h2>{product.company_name}</h2> <h2>{product.description}</h2> <button onClick={}>{!product.watchlist ? 'Add to watchlist':'Remove From watchlist'}</button> </> ) })} </> )}
about 4 years ago · Santiago Trujillo 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