FYI: estoy usando ES6 en ReactJS
tengo un cambiador Necesito que cambie al otro lado cuando se hace clic. Si hace clic en el lado que está actualmente activo no hace nada.
Aquí está mi código de muestra
import { useState } from 'react' const {isLeftButton, setIsLeftButton} = useState(true); const toggleSwitcher = () => { setIsLeftButton(!isLeftButton) } const home = () => { ... return ( <CustomSwitcher isLeftButton={isLeftButton} toggleSwitcher={toggleSwitcher} /> ) ... } export default Home Aquí está el código dentro del CustomSwitcher
const CustomSwitcher = (isLeftButton, toggleSwitcher) => { const leftButton = () => { if (isLeftButton !== true) { toggleSwitcher() } } const rightButton = (isLeftButton, toggleSwitcher) => { if (isRightButton === true) { toggleSwitcher() } } return ( <div> <CustomButton onClick={LeftButton}>Left Button</CustomButton> <CustomButton onClick={rightButton }>Right Button</CustomButton> </div> ) } export default CustomSwitcherSin embargo, obtuve este error.
TypeError: toggleSwitcheris not a function 12 | const CustomSwitcher = () => { 13 | 14 | if (leftButton !== true) { > 15 | toggleSwitcher() | ^ 16 | } 17 | } 18 |Según tengo entendido, al pasar una función a un componente. La función ya no es una función.
Y no creo que mi código sea bueno. Si se te ocurre una forma mejor de hacerlo. Por favor contribuya.
No está utilizando la forma correcta de acceder a los accesorios.
Intenta reemplazar
const CustomSwitcher = (isLeftButton, toggleSwitcher) => {con
const CustomSwitcher = ({isLeftButton, toggleSwitcher}) => {const CustomSwitcher = (isLeftButton, toggleSwitcher) => { ... }
no es la forma correcta de construir un componente.
Usa el objeto props
const CustomSwitcher = (props) => { // props.toggleSwitcher }O desestructurar accesorios
cost CustomSwitcher = ({isLeftButton, toggleSwitcher}) => { ... }Debe usar useState dentro de un componente funcional. En tu caso, dentro de home . Los ganchos no se pueden utilizar a nivel global . En consecuencia, también debe definir toggleSwitcher dentro de home .