我无法通过TouchableOpacity的onPress()调用函数

时间:2020-02-20 16:52:53

标签: react-native touchableopacity

我为什么一直得到TypeError: Chat.onCameraClick is not a function. (In 'Chat.onCameraClick()', 'Chat.onCameraClick' is undefined)有点茫然。

我有以下内容:

export default class Chat extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: 'Chat',
    headerTintColor: colors.HEADERTINT,
    headerStyle: {
      backgroundColor: colors.HEADER,
    },
    headerLeft: () => (
      <TouchableOpacity onPress={() => navigation.dispatch(DrawerActions.openDrawer())}>
        <Icon
          name="menu"
          size={24}
          style={{ color: colors.BLACK, marginLeft: 10 }}
        />
      </TouchableOpacity>
    ),
    headerRight: () => (
      <TouchableOpacity onPress={() => this.onCameraClick()}>
        <Icon
          name="camera"
          type='font-awesome'
          size={24}
          style={{ color: colors.BLACK, marginRight: 10 }}
        />
      </TouchableOpacity>
    ),
  });

进一步,我只有相机方法:

  onCameraClick = () => {
    console.log("Pic!");
  }

我查看了类似RN TouchableOpacity onPress dosn't call function和此处https://facebook.github.io/react-native/docs/touchableopacity的touchableopacity文档的帖子,但是我不确定为什么这是“未定义的”,我也曾尝试仅调用onPress={this.onCameraClick},但基本上同样的事情发生。

我在这里想念什么?

2 个答案:

答案 0 :(得分:0)

我看到您的代码,在其中做了一些修改。现在正在工作。

headerRight: () => (
  <TouchableOpacity onPress={this.onCameraClick}> // <<--- here
    <Icon
  name="camera"
  type='font-awesome'
  size={24}
  style={{ color: colors.BLACK, marginRight: 10 }}
/>
  </TouchableOpacity>
),

在其中调用函数的地方,只需去除圆括号并使其成为一个箭头函数即可。

答案 1 :(得分:0)

之所以不起作用,是因为我从导航类中调用了一个函数,并且该函数可以单独工作。为了使其正常工作,我必须先设置参数,然后在上方进行调用。

添加到我的componentDidMount()

this.props.navigation.setParams({ onCameraClick: this.onCameraClick });

然后将导航更改为:

<TouchableOpacity onPress={navigation.getParam('onCameraClick')}>