react 类暴露_React 组件暴露自身 API 的方法
前言
其實現依賴于:React + TypeScript
問題:如何將一個組件的方法暴露給其他組件呢?
NOTE:以下的方法都不是絕對的,可能會有更好的方式實現,又或者會有更多的方式去暴露子組件的 API,這里只是提供一個思路。
通過 ref
注:本節示例使用的是函數式組件 Ref (Hook)的方式。
這其中有關基本知識如下:
// parent.tsx
import React, {useRef } from "react"
import Child from "./child"
?
const Parent = () => {
const classChildRef: any = useRef(null)
// 調用子組件實例上的 childGet()
const getClassChildFn = () => classChildRef.current.childGet()
return (
獲取子組件值
)
}
export Parent
// child.tsx
import React, {useImperativeHandle, useRef } from "react"
?
// 使用 React.forwardRef() 將 ref 屬性暴露(使得任意一個組件都可以使用該 ref),該函數本身返回一個 React 結點。
// 當你未使用 React.forwardRef 時,大概率會報錯:Cannot add property current, object is not extensible
const Child = React.forwardRef(
(props: any, ref: any) => {
let state = { index: 0 }
const divRef = useRef()
// 第 1 個參數它代表我們需要暴露 ref 屬性。
// 令子組件的 ref 屬性的第2個參數函數返回的對象的屬性暴露出去.
useImperativeHandle(ref, () => (
{
childGet() { console.log(state.index) },
}
))
return (
Child)
}
)
export default Child
當單擊父組件按鈕(獲取子組件值)時,就會調用子組件實例使用 useImperativeHandle Hook 暴露出來的 childGet(),從而在控制臺輸出子組件實例的 state.index 值。
傳遞 props
// parent.tsx
import React from 'react';
import Child from "./child";
const Parent = () => ()
export Parent
// child.tsx
import {useEffect} from 'react';
const Child = (props: any) => {
const sayHello = (v: any) => { console.log(v) }
// 當父組件有向子組件傳遞 props(sayHello) 時,就調用子組件的某個方法,或干脆調用父組件傳遞這個 props.
useEffect(() => props.sayHello
? sayHello(props.sayHello)
: console.error('sayHello is not passed'))
return (
)
}
export default Child;
當在父組件使用子組件時,只需要向子組件傳遞約定的 props,那么子組件將按照某種方式對傳遞的 props 進行處理,或者說是工作。
Child 的靜態屬性
// parent.tsx
import React from 'react';
import Child from "./child";
const Parent = () => ()
Child.say('Yomua'); // 控制臺輸出:Yomua
export default Parent;
// child.tsx
import React from 'react';
const Child = () => (
Child)
// 為 Child 定義靜態屬性
Child.say = (v: any) => { console.log(v) }
export default Child;
由于子組件存在靜態屬性,所以父組件中只要導入子組件,就可以直接使用:子組件.靜態屬性
實例化子組件
// parent.tsx
import React, { Component } from 'react';
import Child from "./child";
const ClassParent = () => {
const getChildValue = () => {
let child = new ClassChild("")
child.childGet(); // 輸出:0
}
return (
獲取子組件值
)
}
export default Parent
// child.tsx
import {Component} from "react"
class ClassChild extends Component {
static childGet: Function;
state: { index: number, }
constructor(props: any) {
super(props)
this.state = { index: 0 }
}
// 這個方法 可以被父組件獲取到(只要父組件實例化子組件即可)
childGet = () => { console.log(this.state.index) }
render() {return (
Child) }
}
export default ClassChild;
由于父組件需要實例化子組件,所以子組件最好使用 class component 的形式,或者使用函數式組件(除了箭頭式的函數式組件除外)
總結
以上是生活随笔為你收集整理的react 类暴露_React 组件暴露自身 API 的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 2022刘润年度演讲:进化的力量关键词
- 下一篇: UE4虚幻引擎,编辑器基础应用,使用技巧
