Unable to use ref to call the child method on a connect redux component

被刻印的时光 ゝ 提交于 2020-01-04 09:26:13

问题


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

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

Like this:

this.childRef0.someMethod
this.childRef1.someMethod

回答1:


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

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()

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



来源:https://stackoverflow.com/questions/49595300/unable-to-use-ref-to-call-the-child-method-on-a-connect-redux-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!