Estoy aprendiendo ReactJS y estaba tratando de devolver un Hello World simple a mi DOM cuando hago clic en el botón.
Además, no hay un error de retorno en la consola, y mi console.log() devuelve el valor correcto cuando hago clic.
const Button = () => { function handleCLick() { console.log('Active') return <h1>Hello World</h1> } return ( <button onClick={handleCLick}>Clique aqui</button> ) } const App = () => { return <Button /> }; export default App;¿Regresar a dónde? El código de manejo de eventos del navegador está llamando a handleClick . Su código no está cerca de donde se pasa el valor de retorno.
Si desea mostrar algún contenido en respuesta a un evento de clic, entonces:
useState para crear un estadoEsto está cubierto en el manual de React.
Prueba esto:
import React, { useState } from 'react'; const App = () => { const [display, setDisplay] = useState(null); const handleClick = () => { setDisplay(display ? null : 'display'); } return ( <> {display && <h1>"Hello world"</h1>} <button onClick={handleCLick}>Clique aqui</button> </> ; }; export default App;Agregar estado: en este ejemplo simple, solo estamos actualizando el elemento h1 .
Mueva el controlador del botón al componente principal y haga que pase el controlador al componente Button para que cuando se haga clic en él, se llame a esa función.
Cuando se llama al controlador, actualice el estado, y el componente se volverá a representar, y h1 tendrá el valor actualizado.
const { useState } = React; function Example() { // Initialise your state const [h1, setH1] = useState('Nothing to see here.'); // Set a new state when the handler is called function handleClick() { setH1('Hello World'); } // Pass the handler function to `Button` // in its props. `h1` will contain the state, // and will be updated when the state changes return ( <div> <h1>{h1}</h1> <Button handleClick={handleClick} /> </div> ); } // `Button` accepts the `handleClick` function // and calls it when it's clicked function Button({ handleClick }) { return ( <button onClick={handleClick} >Clique aqui </button> ); } ReactDOM.render( <Example />, 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>