您现在的位置是:网站首页> 编程资料编程资料
React中父组件如何获取子组件的值或方法_React_
2023-05-24
361人已围观
简介 React中父组件如何获取子组件的值或方法_React_
父组件获取子组件的值或方法
先来说下从哪获取的启发,想要从父组件获取子组件的值或方法。。。
一次写代码的时候,用 Antd 中的 Modal 包裹了一个子组件,子组件中包含 input 输入框,想要在点击对话框上面确定按钮时(即Modal 自带的 onOk方法),拿到其中输入的值
下面用一个父组件(Father.js)和子组件(Hearder.js)来演示如何能拿到值和方法:
方法一
给子组件添加属性 ref='footer'
然后在父组件用 this.refs.footer.xxx 的方式拿值
alert(this.refs.footer.state.sonmsg);//拿到子组件中state中的值 this.refs.footer.run();//拿到子组件中runn方法
方法二
给子组件添加 onRef={(ref) => { this.child = ref; }}
{ this.child = ref; }}>
然后在子组件中添加生命周期的 componentDidMount 这个方法:
componentDidMount() { if (this.props.onRef) { this.props.onRef(this); } }然后在父组件用 this.child.xxx 的方式拿值
alert(this.child.state.sonmsg); this.child.run();
方法三
在父组件创建ref容器:this.pw = React.createRef()
constructor(props) { super(props); // 方法3:创建用来保存ref标识的标签对象的容器 this.pw = React.createRef() }然后给子组件添加属性:ref={this.pw}
然后就可以在父组件用 this.pw.current 拿到子组件值和方法:
alert(this.pw.current.state.sonmsg); this.pw.current.run()
React函数式组件传值之子传父
在用react进行函数式编程时,父组件可以通过props向子组件传值,那么子组件怎么向父组件传值呢?
首先,父组件需要向子组件传递一个函数,然后,子组件通过props获取函数并附上参数,最后,父组件通过函数拿到子组件传递的值。
具体案例
父组件:home.tsx
import React, { useState } from 'react'; import Child from './component/child'; import './index.less'; const Home: React.FC = () => { const [parentCount, setParentCountt] = useState(0); const getChildCount = (val: number) => { setParentCountt(val); }; return ( 我是父组件
子组件传过来的数字:{parentCount}
); }; export default Home; 子组件:child.tsx
import React, { useState } from 'react'; type selfProps = { getCount: Function; }; const Child: React.FC = (props) => { const { getCount } = props; const [count, setCount] = useState(0); const addCount = (val: number) => { setCount(val); getCount(val); }; return ( 子组件
数字:{count}
); }; export default Child; 效果展示

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
相关内容
- Vue中实现过渡动画效果示例代码_vue.js_
- vue进入页面加载数据缓慢实现loading提示过程_vue.js_
- Vue实现让页面加载时请求后台接口数据_vue.js_
- vue再次进入页面不会再次调用接口请求问题_vue.js_
- vue使用keep-alive如何实现多页签并支持强制刷新_vue.js_
- Vue3-KeepAlive,多个页面使用keepalive方式_vue.js_
- 关于vue-admin-element中的动态加载路由_vue.js_
- js如何去除数组中的empty undefined空项_javascript技巧_
- vue导入excel文件,vue导入多个sheets的方式_vue.js_
- vue实现滚动条到顶部或者到指定位置_vue.js_
