📅  最后修改于: 2022-03-11 14:52:54.584000             🧑  作者: Mango
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
doSomething(value)}>Click Me
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a TS error too.
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return {childrenWithProps}
}
};
ReactDOM.render(
,
document.getElementById('container')
);