无法使用 ref 调用连接 redux 组件上的子方法 [英] Unable to use ref to call the child method on a connect redux component

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

问题描述

我想在 renderHiddenItem 中调用 SingleCard 子组件方法.我为每个 renderItem 分配了不同的 ref 名称.但是当我调用this.name 时,它是undefined.这段代码有什么问题吗?我怎样才能做到这一点?

I want to call SingleCard child component methods in renderHiddenItem. I have assigned different ref name for each renderItem. But when I call this.name, it is undefined. Anything is wrong in this code? How can I achieve this?

    <SwipeListView
        data={this.state.listViewData}
        renderItem={(data, i) => {
          const name = 'childRef'+i
          return (
            <SingleCard
              ref={component => this.name = component}
              itm={data.item}
            />
          );
        }}
        renderHiddenItem={(data, i) => {
            const name = 'childRef'+i
            return (
                <TouchableOpacity onPress={ () => console.log(this.name)}>
                  <Text> h </Text>
                </TouchableOpacity>
            );
          }
        }}
      />

更新:我想触发一些写在 singleCard 组件中的动作.需要在 renderHiddenItem 中调用它.

Update: I want to trigger some action which is written in the singleCard component. Need to call that in renderHiddenItem.

像这样:

this.childRef0.someMethod
this.childRef1.someMethod

推荐答案

您需要使用动态变量代替名称,这可以通过使用括号表示法来完成

Instead of name you need to use the dynamic variable which can be done by using the bracket notation

<SwipeListView
    data={this.state.listViewData}
    renderItem={(data, i) => {
      const name = 'childRef'+i
      return (
        <SingleCard
          ref={component => this[name] = component}
          itm={data.item}
        />
      );
    }}
    renderHiddenItem={(data, i) => {
        const name = 'childRef'+i
        return (
            <TouchableOpacity onPress={ () => console.log(this[name])}>
              <Text> h </Text>
            </TouchableOpacity>
        );
      }
    }}
  />

此外,当您在使用 HOC 创建的组件上使用 ref 时,例如 react-redux 中的 connect,大多数库提供一个名为 getWrappedInstance 的方法来获取实际组件的引用,而不是 connect 组件.你可以像

Also when you use ref on a component which is created using an HOC for instance connect from react-redux, most of the libraries provide a method called getWrappedInstance to get the ref for the actual component instead of the connect component. You can use it like

this[name].getWrappedInstance()

但最初您需要将 {withRef: true} 设置为 connect 的第四个参数,用于 SingleCard 就像

but initially you need to set {withRef: true} as the fourth parameter to connect being used in SingleCard like

connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(SingleCard);

您可以在这里阅读更多相关信息

You can read more about it here

https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

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

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