0

i have this two files Home.js and route.js, in routes.js there's a function defined called componentToRoute, this function returns a JSX component. In the Home.js file this function is imported and called, what i want to do is to keep the this binding inside the componentToRoute function as well. I tried doing this with Function.prototype.call() and Function.prototype.bind() but it doesn't work.

routes.js

export function componentToRoute(route) {
  return (
    <View>
      <SearchInput
        section={route.title}
        onInput={this.filterArray(route.key)}></SearchInput>
      <ListOfEntries
        style={style.list}
        onEntryPress={item =>
          this.props.navigation.navigate('Local', {
            item: item,
          })
        }
        list={this.state[route.key]}></ListOfEntries>
    </View>
  );
}

Home.js

import {componentToRoute} from './routes';

class Home extends Component {

filterArray = array => text => {
    this.setState(previousState => {
      return {
        [array]: this.fitlerService.filter(
          previousState['initial' + array],
          'name',
          text,
        ),
      };
    });
  };

renderScene = ({route}) => {
    return componentToRoute(route).call(this);
  };
}

When the renderScene function is executed it throws this.filterArray is undefined, however, if i assing the function to an attribute inside the Home class like :

componentRoute = componentToRoute;

and then call this.componentRoute(route), the function works correctly (this is binded to the correct object).

Do you have any idea why neither call() and bind() work correctly in this case?

1 Answers1

0
componentToRoute(route).call(this);

Do you have any idea why neither call() and bind() work correctly in this case?

The correct syntax to use call here is

componentToRoute.call(this, route);

If the componentToRoute(route) call (in which this was not bound, because it's just a plain function call) wouldn't already have thrown the error about this.filterArray, you would have gotten an exception about the call result not having a .call method - you are returning the JSX object.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375