admin管理员组文章数量:1293272
So as the title suggests I'm just trying to access a parent ponent's method in React via a child ponent. I understand this can be acplished via props, however I'm attempting to do it via an onClick event and it doesn't seem to like that. Here is a basic example of my problem.
var Child = React.createClass({
render: function() {
return (
<button onClick={this.onClick}>Click Here</button>
);
}
});
var Parent = React.createClass({
onClick: function() {
console.log('I've been clicked');
},
render: function() {
return (
<Child />
);
}
});
ReactDOM.render(<Parent />, document.getElementById('Parent'));
How do I get the Child ponent's button onClick event to fire the Parent ponent's onClick method? Appreciate the help.
So as the title suggests I'm just trying to access a parent ponent's method in React via a child ponent. I understand this can be acplished via props, however I'm attempting to do it via an onClick event and it doesn't seem to like that. Here is a basic example of my problem.
var Child = React.createClass({
render: function() {
return (
<button onClick={this.onClick}>Click Here</button>
);
}
});
var Parent = React.createClass({
onClick: function() {
console.log('I've been clicked');
},
render: function() {
return (
<Child />
);
}
});
ReactDOM.render(<Parent />, document.getElementById('Parent'));
How do I get the Child ponent's button onClick event to fire the Parent ponent's onClick method? Appreciate the help.
Share asked Nov 2, 2016 at 23:14 jdev99jdev99 952 gold badges3 silver badges12 bronze badges2 Answers
Reset to default 8You can pass Parent's onClick function to Child as a prop:
<Child myClick={this.onClick} />
and then use it in Child:
<button onClick={this.props.myClick}>Click Here</button>
Entire code:
var Child = React.createClass({
render: function() {
return (<button onClick={this.props.myClick}>Click Here</button>)
}
});
var Parent = React.createClass({
onClick: function() {
console.log("I've been clicked");
},
render: function() {
return (<Child myClick={this.onClick} />);
}
});
ReactDOM.render(<Parent />, document.getElementById('container'));
Thats just the way React is, you can pass it down a reference to the callback function to the child as a prop and then have the child call the function using the prop. This is the React way and cannot be done outside of props when it es to a child accessing a parent property.
if you want to do something more in the child ponent you can define an onclick function inside of your child ponent and have it do anything additional or add arguments to the this.props.onClick
.
本文标签: javascriptAccess a parent component39s method onClick in ReactStack Overflow
版权声明:本文标题:javascript - Access a parent component's method onClick in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741573957a2386173.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论