所需的行为是将参数(文本)传递给 onClick 处理程序以 console.log 它,但似乎我在语法上做错了。
如果我将参数保留如下,则效果很好:
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”。
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>
);
}
}
谢谢
补充: 如果我将其更改为:
onPress={this.onPress.bind('foo')}
它也不起作用。
最佳答案
您可以使用 ES6 在构造函数中进行绑定(bind):
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>
);
}
}
关于binding - react native onPress 与参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017807/