my App ponent like as below:
class App extends Component {
clickHandler = () => {
console.log('click');
}
render() {
return (
<div className="App">
<div onClick={this.clickHandler}>Test1</div>
<Person onClick={this.clickHandler}>Test2</Person>
</div>
);
}
}
And this is my Person ponent:
class Person extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
When i click on Test1
onClick works and show click on console, but when i click on Test2
onClick doesn't work.
how to i handler onClick in parent ponent? i don't want pass onClick to child ponent.
my App ponent like as below:
class App extends Component {
clickHandler = () => {
console.log('click');
}
render() {
return (
<div className="App">
<div onClick={this.clickHandler}>Test1</div>
<Person onClick={this.clickHandler}>Test2</Person>
</div>
);
}
}
And this is my Person ponent:
class Person extends Component {
render() {
return (
<div>{this.props.children}</div>
)
}
}
When i click on Test1
onClick works and show click on console, but when i click on Test2
onClick doesn't work.
how to i handler onClick in parent ponent? i don't want pass onClick to child ponent.
-
Why don't you want to pass
onClick
to the child ponent? That's pretty much how React works, although there are different ways to get properties in children. – Dave Newton Commented Nov 24, 2018 at 19:25
4 Answers
Reset to default 5This should work. Why don't you want to write it this way? You ARE passing it as a prop...
<div onClick={props.onClick}>Test</div>
Here is the plete solution... Checkout: https://codesandbox.io/s/vjp200rj3
Modified render function in App.
render() {
return (
<div className="App">
<div onClick={this.clickHandler}>Test1</div>
<Person clickHandler={this.clickHandler}>Test2</Person>
</div>
);
}
Modified render function in Person:
render() {
return <div onClick={this.props.clickHandler}>{this.props.children}</div>;
}
You need to pass onClick
to the <div>
in Person
.
onClick
is not a special prop that works everywhere in React - The only intrinsic props are key
and children
. Everything else needs to be wired up manually.
The reason your code doesn't work is because you're passing onClick
to Person
, but to the Person
ponent, onClick
is just another prop. It does nothing on it's own until you pass it to a ponent that understands what it means to handle a click event (which all of the built-in ponents in React do).
class Person extends Component {
render() {
return (
<div onClick={propes.onClick}>{props.children}</div>
)
}
}