react-native How to call a function from another c

2019-08-27 07:08发布

问题:

I saw the question relating my question. But I am using connect function in react-persist.

My code

Class A

import B from './B.js';

class A extends Component {
    _onItemPressed(item){
        B.abc();
    }

    render() {
      return (
         <TouchableHighlight
            underlayColor={Colors.colors.lightgrey}
            style={{padding: 15}}
            onPress={this._onItemPressed.bind(this)}>
         <Text>Click Me !</Text>
         </TouchableHighlight>
      );
    }
}

Class B using connect function in react-redux

class B extends Component {

    abc(){
      alert('Hello World');
    }

    render() {
      return (
         <View>
            <Text>Welcome to React Native</Text>
         </View>
      );
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(B);

In my case, How can I call a function?

回答1:

If A and B are not related in any manner(i.e. don't have a parent child relationship), a way to access a component's method in another component is to declare the method as static, however in such a case, you won't be able to access this keyword within it

A

import B from './B.js';

class A extends Component {
    _onItemPressed(item){
        B.abc();
    }

    render() {
      return (
         <TouchableHighlight
            underlayColor={Colors.colors.lightgrey}
            style={{padding: 15}}
            onPress={this._onItemPressed.bind(this)}>
         <Text>Click Me !</Text>
         </TouchableHighlight>
      );
    }
}

B

class B extends Component {

    static abc(){
      alert('Hello World');
    }

    render() {
      return (
         <View>
            <Text>Welcome to React Native</Text>
         </View>
      );
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(B);


回答2:

This approach worked for me.

/* Child.js */
import React from 'react'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './Child.css'

class Child extends React.Component {
  componentDidMount() {
    this.props.onRef(this)
  }
  componentWillUnmount() {
    this.props.onRef(undefined)
  }
  method() {
    alert('do stuff')
  }
  render() {
    return <h1 className={s.root}>Hello World!</h1>
  }
}

export default withStyles(s)(Child);
/* Parent.js */
import React from 'react'
import Child from './Child'

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  }
  render() {
    return (
      <div>
        <Child onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}