binding - react native onPress 与参数绑定(bind)

标签 binding react-native

所需的行为是将参数(文本)传递给 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/

相关文章:

c# - WPF UserControl Dependency Property Setter 未触发

python - Django:无法将上传的图像绑定(bind)到表单 ImageField()

android - AVG 杀毒软件将我的 React Native Android 应用程序检测为恶意软件

facebook - 如何在 React Native 中使用 Facebook Messenger api

c# - 将动态创建的组合框绑定(bind)到 View 模型上的属性

c# - WPF:将转换器应用于 ItemsSource

WPF 风格的绑定(bind)

android - 为什么在 react-native 中将方向从 LTR 更改为 RTL 后我必须重新加载应用程序?

android - 构建React Native应用失败:任务:app:generateDebugBuildConfig FAILED

ios - AppDelegate.m Facebook 和 Twitter handleUrl 函数