248 Teilen
1 Ergebnis
markiert
#children
const Child = ({ doSomething, value }) => (
<button onClick={() => doSomething(value)}>Click Me</button>
);
class Parent extends React.Component{
doSomething = value => {
console.log("doSomething called by child with value:", value);
}
render() {
const childrenWithProps = React.Children.map(this.props.children, child => {
// checking isValidElement is the safe way and avoids a typescript error too
if (React.isValidElement(child)) {
return React.cloneElement(child, { doSomething: this.doSomething });
}
return child;
});
return <div>{childrenWithProps}</div>;
}
}
function App() {
return (
<Parent>
<Child value={1} />
<Child value={2} />
</Parent>
);
}
ReactDOM.render(<App />, document.getElementById("container"));
