本文主要是介绍react 函数式组件通信(父传子、子传父、兄弟之间),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、父传子
例: 通过在父组件中点击按钮打开弹框
Parent.tsx
import { useState } from 'react';
import Child from './Child';
export default function systemFields () {const [modelVisible, setModelVisible] = useState(false)const handleModel = () => {setModelVisible(true)}return (<div className="Parent"><Button onClick={handleModel}>open</Button><Child modelVisible={modelVisible}></Child></div>)
}
Child.tsx
import React, { useState } from 'react';
import { Modal } from 'antd';const Child = (props) => {let { modelVisible } = propsreturn (<><Modal title="Basic Modal" open={modelVisible}><p>Some contents......</p><p>Some contents......</p><p>Some contents......</p></Modal></>);
};
export default Child;
二、子传父
例: 通过在子组件中点击按钮关闭弹框
Child.tsx
import React, { useState } from 'react';
import { Modal } from 'antd';const Child = ({modelVisible, handleCancel}) => {return (<><Modal title="Basic Modal" open={modelVisible} onCancel={()=>handleCancel(false)}><p>Some contents......</p><p>Some contents......</p><p>Some contents......</p></Modal></>);
};
export default Child;
Parent.tsx
import { useState } from 'react';
import Child from './Child';
export default function systemFields () {const [modelVisible, setModelVisible] = useState(false)const handleModel = () => {// 打开弹框setModelVisible(true)}const getIsModalOpen = (isModalOpen) => {//关闭弹框setModelVisible(isModalOpen)}return (<div className="Parent"><Button onClick={handleModel}>open</Button><Child modelVisible={modelVisible} handleCancel={getIsModalOpen}></Child></div>)
}
三、兄弟组件之间传值
借助中间的父组件传值就行
这篇关于react 函数式组件通信(父传子、子传父、兄弟之间)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!