2017-02-22 84 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就是实现这一目标的有效方法。