1

soy nuevo en react y no encuentro la forma de manejar un evento de click en este componente.

const Credit = props => (
  <Card>
   <div className="Credit">
     <img className="icon" src="/icons/money.svg" alt="icono dinero" />
     <p>{props.title}</p>
     <p><span>{props.money}</span></p>
     <ButtonNice onClick={handleClick}>
       {props.button}
     </ButtonNice>
</div>

);

Soy nuevo en react y es la primera vez que manejo un evento de click, todos los eventos de click en la documentación y en cualquier página usan el paradigma de herencia.

este es el ejemplo que viene en la documentación de react

class SignUpDialog extends React.Component {
  constructor(props) {
  super(props);
  this.handleChange = this.handleChange.bind(this);
  this.handleSignUp = this.handleSignUp.bind(this);
  this.state = {login: ''};
}

render() {
  return (
    <Dialog title="Mars Exploration Program" 
       message="How should we refer to you?">
      <input value={this.state.login}
           onChange={this.handleChange} />

    <button onClick={this.handleSignUp}>
      Sign Me Up!
    </button>
  </Dialog>
);
}

handleChange(e) {
  this.setState({login: e.target.value});
}

handleSignUp() {
  alert(`Welcome aboard, ${this.state.login}!`);
}

}

Existe una forma de manejar clicks sobre mi componente basado en composición?

1 respuesta 1

0

Ok i managed to find how to do it.

caveat, you can't pass an event handler directly to the component.

i need to pass it as a prop

const handleClick = (e) => {
  e.preventDefault();
  console.log('hi');
};

const Credit = props => (
  <Card>
    <div className="Credit">
      <img className="icon" src="/icons/money.svg" alt="icono dinero" />
      <p>{props.title}</p>
      <p><span>{props.money}</span></p>
      <ButtonNice clickHandler={handleClick}>
        {props.button}
      </ButtonNice>
    </div>
  </Card>
);

then in my component receive the prop which is the function handling the click

import React from 'react';
import PropTypes from 'prop-types';

import './ButtonNice.scss';

const ButtonNice = props => (
  <button onClick={props.clickHandler} className="ButtonNice btn-transparent">
    {props.children}
  </button>
);

ButtonNice.propTypes = {
  children: PropTypes.string.isRequired,
  clickHandler: PropTypes.func.isRequired,
};

export default ButtonNice;
2
  • hello this is es.stackoverflow.com , so you shoud answer in spanish el 20 ene. 2018 a las 2:41
  • Si es cierto @Daniel Pérez, es la costumbre cuando estoy en stack overflow me pongo en modo inglés. el 30 ene. 2018 a las 15:50

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.