2017-02-22 80 views
0

我是一個noob,目前學習reactjs,有人可以解釋,如何訪問一個component內的功能,在另一個componentreactjs訪問組件內部的函數?

例如:

class ComponentOne extends React.Component{ 
    constructor(){ 
     super() 
     this.handleClick=this.handleClick.bind(this) 
    } 

    handleClick(){ 
     console.log("handling click") 
    } 

    render(){ 
     return(
      <button onClick={this.handleClick}>Click me</button> 
     ) 
    } 
} 

// This component is in another file 

import ComponentOne from './ComponentOne' 

class ComponentTwo extends React.Component{ 
    constructor(){ 
     super() 
     this.handleComp=this.handleComp.bind(this) 
    } 

    handleComp(){ 
     ComponentOne.handleClick() 
    } 

    render(){ 
     return(
      <button onClick={this.handleComp}>Click me</button> 
     ) 

    } 
} 

這樣的事情。

+0

你的意思是訪問屬於父項的函數嗎?還是屬於一個孩子的功能?或者與一個完全不相關的(即不在樹上)組件 – patrick

+0

你能更精確一點,併爲你的問題添加一些代碼? :) – Crocsx

+0

@patrick你可以給任何鏈接或三種方式的例子? – nik7

回答

3

通常當您使用反應並且您想要執行其他組件內部的功能時you use a ref

我有明確的用例,我有一個VideoPlayer組件,我想在播放器上執行播放或暫停功能(組件外),但我想調用VideoPlayer的播放函數來更新它狀態和其他一切。它可以非常強大!

class ParentComponent extends React.Component { 
    handleClick = (e) => { 
     e.preventDefault(); 
     this.childComponentRef && this.childComponentRef.someFunc(); 
    } 
    assignChildComponentRef = target => this.childComponentRef = target; 
    render() { 
     retrurn (<div> 
      <button onClick={this.handleClick}>trigger child function click</button> 
      <ChildComponent ref={this.assignChildComponentRef} prop1={this.something} /> 
     </div>); 
    } 
} 

// child component implementation 
class ChildComponent extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { value: 0 }; 
    } 
    someFunc =() => { 
     this.setState({ value: this.state.value + 1 }); 
    } 
    render() { 
     return <div>{this.state.value}</div> 
    } 
} 

很少有事情要注意。

  1. 你會看到很多使用字符串參考的例子。 This is now considered a bad practice and will be removed in later versions.
  2. 我只會在絕對需要時使用參考。但是,如果您需要參考組件,那麼ref就是實現這一目標的有效方法。