<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}) => {
//子组件的方法,效果是调用传递过来的父组件方法,并且修改state
const 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 }) => {
效果:
点击子组件的按钮后: