带有参数的 react-native onPress 绑定 [英] react-native onPress binding with an argument

查看:33
本文介绍了带有参数的 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 处理程序,它会抱怨无法读取未定义的属性绑定".

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆