所需的行为是将参数(文本)传递给onClick处理程序以进行控制台操作.把它记录下来,但似乎我的语法有问题.

如果我把这个论点省略如下,它就可以正常工作了:

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在构造函数中进行绑定:

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相关问答推荐

我们应该在 react-native 移动应用程序中使用哪个图标库

TypeError:未定义不是对象(判断'theme.spacing [radius]')

React Native - 动画宽度缩小

PanResponder 在第二次拖动时将 Animated.View 捕捉回原始位置

React Native 错误:Animated.event now requires a second argument for options

React Native 上传到 S3 存储空间

从堆栈导航器中删除屏幕

元素中缺少main.jsbundle、Foundation和Security,导致报错

在特定屏幕上使用react-navigation修改后退按钮

使用 Jest 测试 React Native 应用程序

为什么,确切地说,我们需要 React.forwardRef?

更新 this.state.dataSource 不会更新 ListView

如何使用 Expo 在真实的 iOS 设备上运行应用程序?

如何在react-native矢量图标中从多个文件导入图标?

是否需要使用 StyleSheet.create?

react-navigation模式高度

ReactNative TextInput 不可见 iOS

列之间的 React Native FlatList 分隔符

如何使用 Jest 测试导入自定义原生模块的 React Native 组件?

加载字体native-base 错误