react-native如何从另一个用react-redux包装的connect()中的类调用函数?

时间:2018-07-05 10:06:58

标签: reactjs react-native react-redux

我看到the question与我的问题有关。 但是我在react-persist中使用了connect函数。

我的代码

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类在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);

就我而言,如何调用函数?

2 个答案:

答案 0 :(得分:1)

如果A和B没有任何关系(即没有父子关系),则在另一个组件中访问组件方法的一种方法是将该方法声明为静态,但是在这种情况下,您可以将无法访问其中的this关键字

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);

答案 1 :(得分:0)

这种方法对我有用。

/* 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>
    );
  }
}