暂定人事信息保存按钮

react父组件调用子组件中的方法

 

 

 

类组件  

将子组件的this传到父组件,给父组件添加一个属性,值为this,之后就可以通过父组件的属性调用子组件的事件了

 

import React,{Component} from 'react'; // 这是子组件 class A extends Component{ componentDidMount() { this.props.fn(this) } state = { count:1 } render() { let { count } = this.state; return ( <div> 子组件的值: {count} </div> ) } } // 这是父组件 class B extends Component{ // 这个事件是为了拿到子组件的this fn_getThis = (_this) => { this.$child=_this } // 已经拥有子组件this,可以随意调用子组件事件了 increment = () => { this.$child.setState(state => { return {count:state.count+1} }) } render() { return ( <div> <A fn={this.fn_getThis} /> <button onClick={()=>{this.increment()}}> 父组件的按钮 </button> </div> ) } } export default B;

 

函数组件

 

useRef,useImperativeHandle ,forwardRef 3个api的配合使用

useImperativeHandle:可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下, 应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef 一起使用。 语法: useImperativeHandle(ref, createHandle, [deps]) forwardRef:一个函数,返回一个拥有第二个参数的组件

 

import React,{useRef,useImperativeHandle ,forwardRef,useState} from 'react'; // 这是子组件 const A = (props,ref) => { let [count, setCount] = useState(0) useImperativeHandle(ref, () => { return { imcrement:() => { setCount(value => { return value + 1 }) } } }) return ( <div> {count} </div> ) } const NewA = forwardRef(A) // 这是子组件 const B = () => { let refA = useRef(); const fn_sonImcrement = () => { refA.current.imcrement() } return( <div> <NewA ref={refA} /> <button onClick={()=>{fn_sonImcrement()}}>按钮</button> </div> ) } export default B;

 

昨晚梦到了荒唐的事 窝可能是疯了.......

买了一把Ukulele还有一个键盘 很快就会到了 想清楚了也没用有些事

 


__EOF__

本文作者fiamme
本文链接https://www.cnblogs.com/vivin-echo/p/16325613.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   fiamme  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示