react-native - 无法使用带有连接的 ref 调用子方法

标签 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”是未定义的。不使用连接,一切正常。

最佳答案

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

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

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

关于react-native - 无法使用带有连接的 ref 调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51062355/

相关文章:

react-native - 了解 React Native fbsdk 的 'onLoginFinished' 组件上的 'LoginButton' 函数

javascript - 将对象从一个屏幕传递到另一个屏幕 | react native

javascript - 为什么 this.props 返回旧数据?

javascript - 错误 : Actions must be plain objects. 使用自定义中间件进行异步操作。 React-redux 错误

reactjs - 当我更改此 .jsx 文件时,React 未更新。仅当我尝试在服务器上进行更改时才会发生这种情况

javascript - 如何将日期和时间组合成一个日期时间对象?

android - Linking.getInitialURL() 在用于深度链接后未被清除

javascript - React原生上传文件

javascript - Uncaught Error : Actions must be plain objects?

javascript - 如何删除 reducer 内 immutable-js 中的嵌套状态对象?