I am writing a frontend for a site using React JS, I have 2 buttons in the template that look nothing different, I created a component for this button, it renders, everything is fine.

But, I need these two buttons to have different behavior when clicking, how is it better to set this behavior? Somehow to trace two components? Delegate another component? Or is there some kind of decoration system? Impurities? Please tell me how to be better :)

  • one
    It is not necessary to inherit. React preaches composition now. And from the very beginning, the mixin preached, but now it is no longer fashionable. medium.com/@dan_abramov/… - Duck Learns to Take Cover

1 answer 1

Like this...

class Button extends React.Component { // ... } class AwesomeButton extends React.Component { handleChange() { // awesom logic } render() { // передали все свойства и немного поменяли логику... return <Button {...this.props} onChange={this.handleChange} />; } } 
  • hmm, it doesn't work, I think the composition can only be used for links like this, Button -> GroupButton, Photo -> GalleryPhoto, etc. Here primerchik sketched, in theory, when you click on the green square, should alert "ok" by an alert, but for some reason this does not happen, what did I do wrong? - arkadij_ok
  • one
    Well, you don’t process onClick on Button ... add processing and everything is ok ... jsfiddle.net/ou9z7y1e/2 - alexes
  • I added the onClick line: this.props.onClick, - alexes
  • And such a moment, use jsx and ES6 chips, many moments will become much more elegant. gist.github.com/alexesDev/3fe1ff7e67a0a7135c74ba673084551e - alexes
  • Yes, I already use coffeescript, support is of course not very good, but I don’t want to refuse either, so I’m thinking whether to switch to babel or stay on coffee - arkadij_ok