带有参数的react-native onPress绑定 [英] react-native onPress binding with an argument
本文介绍了带有参数的react-native onPress绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所需的行为是将参数(文本)传递给onClick处理程序进行console.log,但似乎语法做错了.
The desired behaviour is to pass an argument (text) to the onClick handler to console.log it but it seems that I'm doing something wrong with the syntax.
如果我按如下所示排除参数,则工作正常:
If I leave the argument out as below, it's working 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>
);
}
}
但是,如果我要将参数传递给onPress处理程序,它将抱怨无法读取未定义的属性" bind".
However, if I want to pass an argument to the onPress handler, it complains 'Cannot read property 'bind' of 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>
);
}
}
谢谢
添加: 如果我将其更改为:
Addition: If I change it to:
onPress={this.onPress.bind('foo')}
它也不起作用.
推荐答案
您可以使用ES6在构造函数中进行绑定:
You can do the binding in the constructor by using ES6:
export default class Nav extends Component {
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
}
然后
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>
);
}
}
这篇关于带有参数的react-native onPress绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文