2016-07-25 2 views
3

Я 2 компоненты A и B, как показано ниже,Доступ к методу другого компонента на React-Native

class A extends Component { 

    testMethodA() { 

    } 

    render() { 
     return (
      <View style={[styles.scene, {backgroundColor: 'red'}]}> 
       <TouchableHighlight onPress={this.onPress}> 
        <Text>Welcome. Press here!</Text> 
       </TouchableHighlight> 
      </View> 
    ); 
    } 
} 


class B extends Component { 

    testMethodB() { 

    } 

    render() { 
     return (
      <View style={[styles.scene, {backgroundColor: 'red'}]}> 
       <TouchableHighlight onPress={this.onPress}> 
        <Text>Welcome. Press here!</Text> 
       </TouchableHighlight> 
      </View> 
    ); 
    } 
} 

Как я могу получить доступ к testMethodA из B и testMethodB от A?

+0

Вы должны пройти в реквизитах. https://facebook.github.io/react/docs/transferring-props.html – Abhishek

ответ

6

Есть два способа получить доступ к другому компоненту методов:

ребенок обращается к родительскому методом - подпирает

class Child extends Component { 
    render() { 
     return (<div>{this.props.formatMessage(10)}</div>) 
    } 
} 

class Parent extends Component { 
    formatMessage(number) { 
     return '$' + number; 
    } 
    render() { 
     return (<Child formatMessage={this.formatMessage} />); 
    } 
} 

родителя обращается к методу ребенка - REFS

class Child extends Component { 
    getInnerData() { 
      return 'some inner data'; 
    } 
    render() { 
     return (<div>child component</div>) 
    } 
} 

class Parent extends Component { 
    componentDidMount() { 
     const childData = this.refs.child.getInnerData(); 
    } 
    render() { 
     return (<Child ref='child' />); 
    } 
} 

Что вы должны сделать, так это иметь общего родителя, который будет хранить данные co mponentA & и переведите его между ними по мере необходимости.

class Child1 extends Component { 
    componentDidMount() { 
     this.props.onMount('child 1'); 
    } 
    render() { 
     return (<div>I'm child1. child2 data is: {this.props.data}</div>) 
    } 
} 

class Child2 extends Component { 
    componentDidMount() { 
     this.props.onMount('child 2'); 
    } 
    render() { 
     return (<div>I'm child2. child1 data is: {this.props.data}</div>) 
    } 
} 

class Parent extends Component { 

    render() { 
     return (
      <div> 
        <Child1 onMount={(msg => this.setState(child1: msg)} data={this.state.child2} /> 
        <Child2 onMount={(msg => this.setState(child2: msg)} data={this.state.child1} /> 
      </div> 
     ); 
    } 
} 

Вы можете также объединить первый & второй методы (реквизита & рефов), чтобы получить методы Componenta & componentB и передать их в качестве опоры, чтобы вы componentB & Componenta соответственно , но это действительно не рекомендуется

Смежные вопросы