2016-11-05 134 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()我们将能够访问对象数组的情况下,儿童功能/组件