React 如何获取组件的实例?

需求是这样的:

多个组件调用A组件的某个方法fn,以实现A组件的内部数据保存。
而且这个fn是动态的,根据不同的组件而变化。

依据我以往的经验:

只要拿到A组件的实例,就可以调用和修改fn

但不知道如何拿到组件的实例?或者其他方式?

谢谢~

阅读 16.4k
3 个回答

ref
this.xxx=React.createRef()

class A extends PureComponent{
        constructor(props){
            super(props);
            this.name=props.name;
        }
        show(){
            alert(this.name)
        }
        render(){
            return(
                    <div>1</div>
            )
        }
    }
    class App extends PureComponent{
        constructor(props){
            super(props);
            this.ref=React.createRef();
            this.show=this.show.bind(this);
        }
        show(){
            this.ref.current.show();
        }
        render(){
            return[
                <input type="button" value="show" onClick={this.show} />,
                <A name={'A'} ref={this.ref} />
            ]
        }
    }

类似这样?

首先我不清楚你的这种需求是怎么产生的。

多个组件调用A组件的某个方法fn,这种完全可以根据组件通信去解决,不建议使用这种“黑科技”

如果只是学术上的问题 如何拿到组件的实例

那么很简单,react提供了一种方法就是this.refs api

比如

// this.refs.div
<div ref="div" />

这个api已经废弃了,现在的写法是这样的

// this.div 现在就是div的引用了
<div ref={ref => this.div = ref} />

在最新的react16.3中api进行了再次升级,现在的写法是这样的。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    // const node = this.myRef.current; 这样可以拿到组件实例
    return <div ref={this.myRef} />;
  }
}

建议直接看官方文档, https://reactjs.org/docs/refs...

希望我的回答对你有帮助。

感觉react和reudx做逻辑比较多的项目,很不灵活,不好用,也不知道是不是我用法的问题,数据流很乱,乱的吐血

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题