父传子

①在父组件中定义const nameFromParent: string = "John";

②从父组件传递给子组件

③在子组件中定义属性的类型interface ChildProps { age: number;}

④如果数据多需要解构再使用const { name,... } = props;,如果只有一个参数也可以直接卸载函数的参数括号中

⑤在子组件中使用

Child Component

import React from 'react';// 子组件interface ChildProps {name: string;age: number;handleClick: () => void;}const ChildComponent: React.FC<ChildProps> = (...props) => {const { name, age, handleClick } = props;return (<div><p>Child Component</p><p>Name: {name}</p><p>Age: {age}</p><button onClick={handleClick}>Click me</button></div>);};// 父组件const ParentComponent: React.FC<ParentProps> = () => {const nameFromParent: string = "John";const ageFromParent: number = 25;const handleClick = () => {console.log('Button clicked!');};// 使用 {...props} 将所有属性传递给子组件return (<div><p>Parent Component</p><ChildComponent name={nameFromParent} age={ageFromParent} handleClick={handleClick} /></div>);};export default ParentComponent;

子传父

①在父组件中定义事件名称并赋予点击事件

②在父组件中实现点击事件const handleDataFromChild = (data: string) => {};

③在子组件中定义事件类型interface ChildProps {sendDataToParent: (data: string) => void;}

④如果数据多需要解构再使用const { sendDataToParent,... } = props;,如果只有一个参数也可以直接卸载函数的参数括号中

⑤在子组件中定义点击事件并

⑥并在子组件中实现点击事件调通过父组件传过来的事件传递参数const sendData = () => {sendDataToParent(data); };

另外如果想不点击直接发送参数的话可以在useEffect(() => {sendDataToParent(data);},[sendDataToParent])

import React from 'react';// 子组件interface ChildProps {sendDataToParent: (data: string) => void;}const ChildComponent: React.FC<ChildProps> = ({ sendDataToParent }) => {const sendData = () => {const data = "Data from Child";// 在需要的时候调用回调函数传递信息给父组件sendDataToParent(data);};return (<div><p>Child Component</p><button onClick={sendData}>Send Data to Parent</button></div>);};// 父组件const ParentComponent: React.FC<ParentProps> = () => {const handleDataFromChild = (data: string) => {console.log('Data received from Child:', data);// 在这里处理从子组件接收到的数据};return (<div><p>Parent Component</p>{/* 将回调函数传递给子组件 */}<ChildComponent sendDataToParent={handleDataFromChild} /></div>);};export default ParentComponent;