无法使用带有连接的引用的子方法

时间:2018-06-27 12:04:31

标签: react-native react-redux

我想从子组件中调用方法,如此处建议的Call child method from parent

但是,当子组件用react-redux的connect包裹起来时,它是不起作用的,如下例所示:

子组件

interface OwnProps {
  style?: any;
}
interface ReduxStateProps {
  category: string;
}
interface DispatchProps {
  updateTimestamp: (timestamp: Date) => void;
}
type Props = ReduxStateProps & DispatchProps & OwnProps;

interface State {
  timestamp?: Date;
}

class ChildComponent extends React.Component<Props, State> {
  childMethod = () => {
    console.log("I am the child");
  };

  render(){
      <Text>Debug</Text>
  }
}

function mapStateToProps(state: any): ReduxStateProps {
  return {
    category: state.menu.category
  };
}

function mapDispatchToProps(dispatch: Dispatch<any>): DispatchProps {
  return {
    updateTimestamp: (timestamp: Date) =>
      dispatch(updateTimestampActionCreator(timestamp))
  };
}

export default connect<ReduxStateProps, DispatchProps, OwnProps>(
  mapStateToProps,
  mapDispatchToProps
)(ChildComponent);

父组件

class ParentComponent extends React.Component<{},{}> {
  private childComponent: any;

  render(){
    <View>
      <ChildComponent ref={ref => this.childComponent = ref as any}>
    </View>
  }
}

在此处,在父组件中使用ref时,方法“ childMethod”未定义。不使用连接,一切正常。

1 个答案:

答案 0 :(得分:6)

这样做通常被标记为不良做法。通常更好的方法是执行以下操作。

class Parent extends React.Component {

   state = {
       functionToCallInChild = null;
   }

   render() {
       return (
           <Child setCallable={callable => this.setState({functionToCallInChild: callable})}/>
       );
   }
}

class Child extends React.Component {

    componentDidMount() {
       this.props.setCallable(this.childFunction);
    }

    childFunction = () => console.log("It worked!");

    render() {
       return (</div>);
    }
}

您可以看到,一旦子级渲染,父级现在就可以调用该子级的功能。