功能不是功能 - 反应原生

时间:2018-04-25 11:42:45

标签: react-native

在我的项目中,我使用了堆栈导航器作为导航器。在navigationOptions里面,在headerRight中,我使用了一个自定义按钮。当我尝试调用onPress时,它说该函数不是函数。

这是函数

  sharePost() {
    // this.props.doShare();
    console.log("DONE");
  }

我已将完整代码放在此处。我想在navigationOptions的rightHeader中使用sharePost函数。

     import React, { Component } from "react";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  Animated,
  ScrollView,
  StyleSheet,
  Dimensions
} from "react-native";

import { PostProfileBar, WritePost } from "../../components";
import { ButtonWithoutBackground } from "../../mixing/UI";

const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height / 3;

class SharePostScreen extends Component {
  constructor(props) {
    super(props);

  sharePost() {
    // this.props.doShare();
    console.log("DONE");
  }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <WritePost profile={this.state.loggedUserProfile} />

          <View style={styles.sharePostWrapper}>
            <PostProfileBar profile={this.state.postedUserProfile} />

            <Image
              source={{
                uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
              }}
              resizeMode={"stretch"}
              style={styles.image}
            />
          </View>
        </ScrollView>
      </View>
    );
  }

  static navigationOptions = ({ navigation }) => ({
    headerTitle: "Share To Feed",
    headerTitleStyle: {
      paddingLeft: "20%",
      paddingRight: "20%"
    },
    headerStyle: {
      paddingRight: 10,
      paddingLeft: 10
    },
    headerLeft: (
      <Icon
        name={"close"}
        size={30}
        onPress={() => {
          navigation.goBack();
        }}
      />
    ),
    headerRight: (
      <ButtonWithoutBackground
        buttonText={styles.buttonText}
        onPress={this.sharePost()}
      >
        Post
      </ButtonWithoutBackground>
    )
  });
}

1 个答案:

答案 0 :(得分:3)

要在class level methods方法static内拨打navigationOptions,您可以执行以下操作,

// Bind function using setParams

componentDidMount() {
  const { navigation } = this.props;
  navigation.setParams({
    referencedSharePost: this.sharePost,
  });
}

sharePost = (parameters) => {
    // this.props.doShare();
    console.log("DONE" + parameters);
  }

static navigationOptions = ({ navigation }) => {
  const { params = {} } = navigation.state;
  return {
     //... Other Options
     headerRight: (
      <ButtonWithoutBackground
        buttonText={styles.buttonText}
        onPress={() => params.referencedSharePost("I'm passing something")}
      >
        Post
      </ButtonWithoutBackground>
    )
  }
}