Pergunta

I was trying to add a click handler to my own child component. In react chrome extension I was able to see the click handler as well.

But the click itself didn't work - wondering what did I miss.

Sample Code:

... 
render (
  <MySampleComponent onClick={this.handler} />
);
...
Foi útil?

Solução

MySampleComponent can take whichever props it wants; components don't automatically copy props to their children. If you want to be able to add an onClick handler to MySampleComponent, then you can support this in the definition of that component:

var MySampleComponent = React.createClass({
  render: function() {
    return <div onClick={this.props.onClick}>...</div>;
  }
});

Outras dicas

You can add the handler from the samecomponent or call it through props. Below code looks for onClick param in props. If nothing is passed, then it goes for default handler in the component(clickHandler).

var MySampleComponent = React.createClass({
  clickHandler: function(){
       // write your logic
  },
  render: function() {
    return <div onClick={this.props.onClick || this.clickHandler}>...</div>;
  }
});

and while using this in another component use it as below

...........
handler: function() {
   // write your logic 
},
render {
  var self = this;
  return (<MySampleComponent onClick={self.handler} />);
 }

......
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top