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?
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>
One can use HTML data-* Attributes.
someFunction
someFunction= (event)=>{
console.log(event.target.dataset.mykey )
}
render:
<Button data-mykey onPress={this.someFunction} />
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
<SomeButton onPress={this.someFunction.bind(this, args)} />?