react如何在父组件中调用子组件事件
生活随笔
收集整理的這篇文章主要介紹了
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{// 這個事件是為了拿到子組件的thisfn_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;總結
以上是生活随笔為你收集整理的react如何在父组件中调用子组件事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 饼家常做法?
- 下一篇: 饮料价格为什么越来越贵?