📌  相关文章
📜  将道具传递给孩子 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:00.910000             🧑  作者: Mango

代码示例1
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') );