/** @jsx React.DOM */
var Button = React.createClass({
handleClick: function(){
console.log(' FROM BUTTON')
},
render: function() {
return <input type='button' onClick={this.handleClick} value={this.props.dname}/>;
}
});
var Text = React.createClass({
render: function() {
return <input type='text' onClick={this.handleClick} value={this.props.ival}/>;
}
});
var search = React.createClass({
handleClick: function() {
console.log('searching')
},
render: function(){
return (
<div>
<Text/>
<Button dname={this.props.dname} onClick={this.handleClick} />
</div>
);
}
});
React.renderComponent(<search dname='Look up' fname='Search'/> , document.body);
I have created a button and text component and included them in a search component now i want to override the default handleClick event of button with search component's handler. But this.handleClick is pointing to button component's event handler.. please help.. i need FROM SEARCH on click instead i got FROM BUTTON..
First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.
You are 99% percent there.
React uses a one-way data-flow. So, events on nested components will not propagate to their parents.
You must propagate events manually
Change your <Button>
s handleClick
function to call the this.props.handleClick
function passed in from it's <Search>
parent:
var Button = React.createClass({
handleClick: function () {
this.props.onClick();
},
...
});
Attached is a fiddle of your original post, with the required change. Instead of logging FROM BUTTON
, it will now alert searching
.
http://jsfiddle.net/chantastic/VwfTc/1/
You need to change your Button
component to allow such behaviour:
var Button = React.createClass({
handleClick: function(){
console.log(' FROM BUTTON')
},
render: function() {
return (
<input type='button'
onClick={this.props.onClick || this.handleClick}
value={this.props.dname} />
);
}
});
note the onClick={this.props.onClick || this.handleClick}
.
That way if you pass an onClick
prop when instantiating Button
it will have a preference over the Button
's handleClick
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With