2

So, i've readed that doing something like this

<SomeButton onPress={() => { this.someFunction(args)}} />

is bad because it is creating a new instance of function for each render cycle.

But how do i pass args in React-Native then?

3
  • Have you tried <SomeButton onPress={this.someFunction.bind(this, args)} />? Commented Jul 27, 2018 at 10:03
  • Is not this the same thing? Commented Jul 27, 2018 at 10:04
  • Oh you are right, this also creates a new function on every render. My bad. Commented Jul 27, 2018 at 10:06

3 Answers 3

1

Creating a new inline function is fine in many cases, but if you have a lot of SomeButton components it might be worth passing the args as props to the component and use that as arguments in the component's onPress instead.

Example

class SomeButton extends React.Component {
  handleClick = () => {
    const { onClick, someProp } = this.props;
    onClick(someProp);
  };

  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}

class App extends React.Component {
  handleClick = arg => {
    console.log(arg);
  };

  render() {
    return <SomeButton onClick={this.handleClick} someProp="foo" />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

One can use HTML data-* Attributes.

someFunction

someFunction= (event)=>{
  console.log(event.target.dataset.mykey )
}

render:

<Button data-mykey onPress={this.someFunction} />

Comments

0

In which context? I would say it depends if that is what you want or need to have. In general you could use properties instead of passing arguments.

I guess you read something about re-rendering (which may result in loss of performance); here is what is said about it in the react-native guide: https://facebook.github.io/react-native/docs/direct-manipulation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.