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

vbv*_*bvx 4 react-native react-redux

我想从子组件中调用一个方法,按照这里的建议从父组件中调用子方法

但是,当子组件用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);
Run Code Online (Sandbox Code Playgroud)

父组件

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

  render(){
    <View>
      <ChildComponent ref={ref => this.childComponent = ref as any}>
    </View>
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Fra*_*och 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>);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到,子级渲染后,父级现在可以调用该子级的函数。

  • 你能详细说明一下为什么这是一种不好的做法吗?此外,您的方法解决了我的问题,但没有回答最初的问题,所以我认为我不能将其标记为已接受的答案 (3认同)