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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,292评论 19 139
  • vue概述 在官方文档中,有一句话对Vue的定位说的很明确:Vue.js 的核心是一个允许采用简洁的模板语法来声明...
    li4065阅读 12,006评论 0 25
  • 你在时间的哪里 遇见了几个知音 温柔和热情 有多少被珍惜 多少被辜负丢弃 快乐变得敏感 悲伤变得麻木 想爱不敢爱的...
    晚风不晚阅读 2,790评论 1 3
  • 休闲一刻
    丽酷阅读 1,176评论 0 0
  • 02 萧萧 那武士停了步,云郎一手扶案,一手捂着肚子站起身,急道:“公主莫怪。在下忽觉肚子里有些闹腾,这位健儿...
    宇文歡阅读 5,117评论 3 10