react如何将组件内部的方法暴露给外部

最近在项目中遇到一个问题,就是需要在类的外部调用操作类内部的方法。

举个例子,我有一个Toast组件,在外部需要调用它的show方法来控制他的显隐状态。
之前我的写法是写一个静态类方法,然后在constructor中去修改它的作用域,代码如下:

// @flow
import React from 'react';
import './style.less';

type Props={
    time:number,
    text:string,
}

export default class Toast extends React.Component {
    static show({ text }) {
        const _self = this;
        this.setState({
            isShow: true,
            text,
        }, () => {
            _self.timer = setTimeout(() => {
                this.setState({
                    isShow: false,
                });
            }, this.props.time);
        });
    }

    constructor(props:Props) {
        super(props);
        this.state = {
            isShow: false,
            text: '',
        };
        Toast.show = Toast.show.bind(this);
    }

    componentWillUnmount() {
        this.setState({
            isShow: false,
        });
        clearInterval(this.timer);
    }

    render() {
        const { isShow, text } = this.state;
        return (
            <div className="toast-wrapper">
                {isShow && <div className="toast">{text}</div>}
            </div>
        );
    }
}

后来发现bug频出,只有在重新刷新的时候show方法中调用this.setState()才有效,而在多个页面使用这个组件会出现很多问题,都是由于作用域绑定错误的原因。

解决方法

最后审视了下代码,应该是将静态的show方法指向内部的show方法,而不是把静态的show方法的上下文绑定到这个类上。

调整代码如下:

// ...
 constructor(props:Props) {
        super(props);
        this.state = {
            isShow: false,
            text: '',
        };
        Toast.show = this.show.bind(this); // 最重要的一步!!
    }

    show({ text }) {
        const _self = this;
        this.setState({
            isShow: true,
            text,
        }, () => {
            _self.timer = setTimeout(() => {
                this.setState({
                    isShow: false,
                });
            }, this.props.time);
        });
    }
// ....

还是因为自己对bind理解不深刻的原因,看下mdn–bind

React中,函数式组件通常不直接支持通过`ref`访问并调用子组件方法,因为函数式组件没有传统的生命周期方法和实例状态。但是,你可以通过以下几种方式间接地实现这个目标: 1. **forwardRef** API:`forwardRef`是一个高阶函数,可以让你将`ref`传递给子组件,并从外部接收一个回调,这个回调可以在适当的时候调用子组件方法。 ```jsx import { forwardRef } from 'react'; function ParentComponent({ childProps }) { const childRef = React.useRef(null); const handleClick = () => { if (childRef.current) { childRef.current.childMethod(); } }; return ( <ChildComponent ref={childRef} {...childProps} /> // 在需要的地方添加按钮事件处理,触发 handleClick <button onClick={handleClick}>Call Child Method</button> ); } const ChildComponent = forwardRef((props, ref) => { // ... useEffect(() => { // 当子组件挂载后,设置子方法可被外部引用 ref.current = { childMethod }; }, [ref]); // ... }); ``` 2. **useImperativeHandle**:如果你确定子组件暴露了某个特定的方法,可以使用`useImperativeHandle`来提供一个自定义的API,让父组件能够像操作DOM元素一样调用它。 ```jsx import React, { useRef, useImperativeHandle } from 'react'; function ParentComponent({ childProps }) { const childRef = useRef(null); useImperativeHandle(childRef, () => ({ callChildMethod: () => { childRef.current.callChildMethod(); }, })); // 使用 ImperativeHandle 的 API return ( <ChildComponent ref={childRef} {...childProps} /> // ... <button onClick={() => childRef.current.callChildMethod()}>Call Child Method</button> ); } // ...在 ChildComponent 中定义 callChildMethod 方法 ``` 请注意,在实际应用中,尽量避免过度依赖`ref`直接操作子组件内部的状态或方法,除非有非常明确的需求。通常,更好的做法是利用 props 和 React 的其他特性来管理组件间通信。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值