Response-native onPress binding with argument

The desired behavior is to pass the argument (text) to the onClick handler for console.log, but it seems like I'm doing something wrong with the syntax.

If you leave the argument below, it works fine:

export default class Nav extends Component { componentDidMount() { this.props.pickNumber(3); } onPress() { console.log('FOOOBAAR'); } render() { return ( <View> <Text>####################</Text> <Text>Intro Screen</Text> <Text>Number: {this.props.numbers}</Text> <TouchableHighlight onPress={this.onPress.bind(this)}> <Text>Go to Foo</Text> </TouchableHighlight> </View> ); } } 

However, if I want to pass an argument to the onPress handler, it complains: "Cannot read the bind property from undefined.

 export default class Nav extends Component { componentDidMount() { this.props.pickNumber(3); } onPress(txt) { console.log(txt); } render() { return ( <View> <Text>####################</Text> <Text>Intro Screen</Text> <Text>Number: {this.props.numbers}</Text> <TouchableHighlight onPress={this.onPress('foo').bind(this)}> <Text>Go to Foo</Text> </TouchableHighlight> </View> ); } } 

thanks

Addition: If I change it to:

 onPress={this.onPress.bind('foo')} 

it doesn't work either.

+7
react-native binding
source share
3 answers

You can bind in the constructor using ES6:

 export default class Nav extends Component { constructor(props) { super(props); this.onPress = this.onPress.bind(this); } 

and then

  onPress(txt) { console.log(txt); } render() { return ( <View> <Text>####################</Text> <Text>Intro Screen</Text> <Text>Number: {this.props.numbers}</Text> <TouchableHighlight onPress={() => this.onPress('foo')}> <Text>Go to Foo</Text> </TouchableHighlight> </View> ); } } 
+16
source share

You can avoid the function binding in the constructor by binding it to the onPress value and passing the argument after 'this'. The constructor is drawn perfectly, but the more I enter the ground of the TOE, the more unpleasant it feels. You can reorganize your code so

 export default class Nav extends Component { componentDidMount() { this.props.pickNumber(3); } onPress(txt) { console.log(txt); // foo } render() { return ( <View> <Text>####################</Text> <Text>Intro Screen</Text> <Text>Number: {this.props.numbers}</Text> <TouchableHighlight onPress={this.onPress.bind(this,'foo')}> <Text>Go to Foo</Text> </TouchableHighlight> </View> ); } } 

The first argument is 'this', and any other arguments can be sent after it, which will be received in the same order.

+7
source share

You can also solve this with thick arrows:

 export default class Nav extends Component { handlePress = (text) => { console.log(text); } render() { return ( <View> <Text>####################</Text> <Text>Intro Screen</Text> <Text>Number: {this.props.numbers}</Text> <TouchableHighlight onPress={() => this.handlePress('weeeeee')}> <Text>Go to Foo</Text> </TouchableHighlight> </View> ); } } 
+2
source share

All Articles