2016-11-05 213 views
1

我有1個父組件名稱[Parent-1]和1個子組件名稱[Child-1]。現在,我還有其他幾個組件名稱[Other-1]和[Other-2]。兒童組件通訊

現在我將[Other-1]和[Other-2]組件傳遞給[Child-1]組件。 JSX渲染正確。我如何從[Child-1]訪問[Other-1/2]組件功能?或者我如何將道具從[Other-1/2]傳遞給[Child-1]?

通過使用引用我可以從[Parent-1]調用[Other-1/2]函數,但我想從[Child-1]訪問。我嘗試將參數傳遞給[Child-1],如<Child abc={() => this.refs.other1.hello()}/><Child abc={this.refs.other1.hello()}/>,但這不起作用。

通過使用全局事件發射器的方式,我能夠實現解決我的上述問題。但不知道這是否是React.js中的適當方式

回答

1

我認爲您沒有正確使用refs

當您嘗試給arrow function進行參考時,由於ref返回null,有時會導致錯誤。請參閱my question以瞭解原因。

的例子會幫助你理解refs

希望這有助於!

class Others1 extends React.Component { 
 
    log(){ 
 
    console.log('Hello from Others1') 
 
    } 
 
    render() { 
 
    return <h1>Others1</h1> 
 
    } 
 
} 
 

 
class Others2 extends React.Component { 
 
    log(){ 
 
    console.log('Hello from Others2') 
 
    } 
 
    render() { 
 
    return <h1>Others2</h1> 
 
    } 
 
} 
 

 

 
class Child extends React.Component{ 
 
    other1Ref(el) { 
 
    el.log() 
 
    } 
 
    other2Ref(el) { 
 
    el.log() 
 
    } 
 
    render() { 
 
    const Others1 = this.props.others1 
 
    const Others2 = this.props.others2 
 
    return (
 
     <div> 
 
     <Others1 ref={this.other1Ref}/> 
 
     <Others2 ref={this.other2Ref}/> 
 
     </div> 
 
    ) 
 
    } 
 
    
 
} 
 

 
class Parent extends React.Component{ 
 
    render() { 
 
    return <Child others1={Others1} others2={Others2}/> 
 
    } 
 
} 
 

 
ReactDOM.render(<Parent/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+0

此外還得到幫助從http://andrewhfarmer.com/component-communication/ –

+0

雖然還有1個問題ReactDOM.findDOMNode(this.refs.something)在放入log()函數並從Child –

+0

調用log()函數時總是返回null'this.refs.something'被稱爲字符串refs和那些已被棄用。 –

0

此外,可以有在這裏我們必須通過[其他1]和[其他2]作爲對象的陣列說例如的情況下

class Others1 extends React.Component { 
    log(){ 
    console.log('Hello from Others1'); 
    } 
    render() { 
    return <h1>Others1</h1> 
    } 
} 

class Child extends React.Component{ 
    other1Ref(el) { 
    el.log(); 
    } 

    render() { 

    // 'i' need to be counter for eg. 0, 1, 2 ... 
    const Others1 = this.props._array[i].type(); 
    Other1.other1Ref(); 

    return (
     <div></div> 
    ) 
    } 

} 

let _array = [<Others1/>, ...]; 

class Parent extends React.Component{ 
    render() { 
    return <Child _array={_array} /> 
    } 
} 

ReactDOM.render(<Parent/>, document.getElementById('app')) 

通過使用.TYPE()我們將能夠訪問對象數組的情況下,兒童功能/組件