鍍金池/ 問答/HTML/ React 如何獲取組件的實例?

React 如何獲取組件的實例?

需求是這樣的:

多個組件調(diào)用A組件的某個方法fn,以實現(xiàn)A組件的內(nèi)部數(shù)據(jù)保存。
而且這個fn是動態(tài)的,根據(jù)不同的組件而變化。

依據(jù)我以往的經(jīng)驗:

只要拿到A組件的實例,就可以調(diào)用和修改fn

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

謝謝~

回答
編輯回答
雨萌萌

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} />
            ]
        }
    }

類似這樣?

2017年11月7日 08:22
編輯回答
安若晴

感覺react和reudx做邏輯比較多的項目,很不靈活,不好用,也不知道是不是我用法的問題,數(shù)據(jù)流很亂,亂的吐血

2018年3月13日 16:32
編輯回答
荒城

首先我不清楚你的這種需求是怎么產(chǎn)生的。

多個組件調(diào)用A組件的某個方法fn,這種完全可以根據(jù)組件通信去解決,不建議使用這種“黑科技”

如果只是學術上的問題 如何拿到組件的實例

那么很簡單,react提供了一種方法就是this.refs api

比如

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

這個api已經(jīng)廢棄了,現(xiàn)在的寫法是這樣的

// this.div 現(xiàn)在就是div的引用了
<div ref={ref => this.div = ref} />

在最新的react16.3中api進行了再次升級,現(xiàn)在的寫法是這樣的。

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...

希望我的回答對你有幫助。

2017年1月29日 02:55