无法使用带有连接的 ref 调用子方法 [英] Can't call child method using a ref with connect

查看:43
本文介绍了无法使用带有连接的 ref 调用子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to call a method from a child component, as per suggested here Call child method from parent

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

However, it doesn't work when the child component is wrapped with connect from react-redux as in the example below:

子组件

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"是未定义的.不使用连接,一切正常.

Here, the method "childMethod" is undefined when using the ref in the parent component. Without using connect, everything works fine.

推荐答案

这样做通常被标记为不好的做法.另一种通常更好的方法是执行以下操作.

Doing this is generally labelled as bad practice. Another option that is generally a much better approach is to do the following.

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

你可以看到,一旦子渲染,父现在可以访问调用子的函数.

You can see, once the child renders, the parent now has access to call the child's function.

这篇关于无法使用带有连接的 ref 调用子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆