Unable to use ref to call the child method on a co

2019-07-21 09:43发布

问题:

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