您的位置:首页 > 教育 > 锐评 > 网络培训心得体会500字_中国电商网官网_seo站长平台_seo优化网站

网络培训心得体会500字_中国电商网官网_seo站长平台_seo优化网站

2025/5/25 9:35:04 来源:https://blog.csdn.net/y523648/article/details/142920141  浏览:    关键词:网络培训心得体会500字_中国电商网官网_seo站长平台_seo优化网站
网络培训心得体会500字_中国电商网官网_seo站长平台_seo优化网站
<script type="text/babel" data-type="module">
import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';const ParentComponent = () => {const [message, setMessage] = useState("")//父组件方法,将传递给子组件const handleChildAction = (childMessage) => {setMessage(childMessage)  //效果是接收子组件传来的数据,并修改state}const parentMessage = "Hello I'm a parent component" //传递给子组件的数据return (<div style={{padding: '20px', border: '1px solid Red', width: '400px'}}><p>父组件</p><ChildComponent onAction={handleChildAction} fromParent={parentMessage} /><p>来自子组件的消息:{message}</p></div>)
}const ChildComponent = ({onAction, fromParent}) => {//子组件的方法,效果是调用传递过来的父组件方法,并且修改stateconst handleClick = () => {onAction('我是子组件的消息,我收到了你的消息:' + fromParent)}return (<div style={{padding: '20px', border: '1px solid black', width: '300px'}}><p>子组件</p><button onClick={handleClick}>发送消息给父组件</button></div>)
}const root = createRoot(document.getElementById('root'));
root.render(<StrictMode><ParentComponent /></StrictMode>
);
</script>

需要注意的是,如果是TypeScript,需要指定参数的类型是方法

interface ChildComponentProps {onAction: (message: string) => void; 
}const ChildComponent: React.FC<ChildComponentProps> = ({ onAction }) => {

效果:

点击子组件的按钮后:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com