Digamos que quiero mostrar una copia diferente (por ejemplo, "zapatos") dependiendo del texto en la cadena {variant_prod.title}
Así por ejemplo:
if (variant_prod_title == 'Nike air shoes' ) { Change so "shoes" will be the only thing showing in the string else if (variant_prod_title == 'Nike air t-shirt' ) { Change so "t-shirt" will be the only thing showing in the string } }Así es como se ve el código para mí en mi componente de reacción, ¿cómo cambio para que solo muestre "zapatos", por ejemplo?
<span class="uppsell-add-to-cart-copy">{variant_prod.title}</span>Si su título tiene una estructura consistente y siempre tiene la salida como el tercer valor en la cadena, simplemente puede usar
<span class="uppsell-add-to-cart-copy">{variant_prod.title.split(' ')[2]}</span> variant_prod.title.split(' ') convertirá el título en una matriz de 3 elementos y puede usar el valor que desee
Las 'zapatillas Nike Air' devolverán las shoes
Volverá t-shirt 'Nike air t-shirt'
'Nike air cualquier otra cosa' devolverá anything-else
Así es como puede lograr esto de una manera que no importa si su título es 'Zapatillas Nike Air' o 'Zapatillas Puma'. Siempre que incluya zapatos o camiseta, el valor mostrado se establecerá en consecuencia.
// this sets the initial value to the entire string let displayedValue = variant_prod.title; // this if checks if the word eg 'shoes' or 't-shirt' is present in the title if (variant_prod.title.includes('shoes')) { displayedValue = 'shoes'; } else if (variant_prod.title.includes('t-shirt')) { displayedValue = 't-shirt'; } return ( <span class="uppsell-add-to-cart-copy">{displayedValue}</span> )Una forma sencilla de implementar lo que está buscando es mediante el uso del operador condicional (ternario)
Es una buena práctica usar la comparación estricta "===" y declarar sus comparaciones en una variable.
Puede probar el siguiente código usando ES6:
const NIKE_AIR_SHOES = 'Nike air shoes'; const NIKE_AIR_TSHIRT = 'Nike air t-shirt'; <span class="uppsell-add-to-cart-copy"> {variant_prod.title === NIKE_AIR_SHOES ? "Shoes" : variant_prod.title === NIKE_AIR_TSHIRT ? "t-shirt" : ""} </span>También puede usar el operador lógico AND (&&) así como el operador lógico OR (||) para implementar esto.
<span class="uppsell-add-to-cart-copy"> {(variant_prod.title === NIKE_AIR_SHOES && "Shoes") || (variant_prod.title === NIKE_AIR_TSHIRT && "t-shirt") || ""} </span>;