Thomas
Thomas

Reputation: 2386

React Native Navigation - Action using Component's State

I've made a full-screen TextInput and would like to have an action performed when the Post button in the NavigationBar is pressed. However, because I have to make the method that the Button is calling in the onPress prop a static method, I don't have access to the state.

Here is my current code, and the state comes up undefined in the console.log.

import React, { Component } from 'react';
import { Button, ScrollView, TextInput, View } from 'react-native';
import styles from './styles';

export default class AddComment extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: 'Add Comment',
      headerRight: (
        <Button
          title='Post'
          onPress={() => AddComment.postComment() }
        />
      ),
    };
  };

  constructor(props) {
    super(props);
    this.state = {
      post: 'Default Text',
    }
  }

  static postComment() {
    console.log('Here is the state: ', this.state);
  }

  render() {     
    return (
      <View onLayout={(ev) => {
        var fullHeight = ev.nativeEvent.layout.height - 80;
        this.setState({ height: fullHeight, fullHeight: fullHeight });
      }}>
        <ScrollView keyboardDismissMode='interactive'>
          <TextInput
            multiline={true}
            style={styles.input}
            onChangeText={(text) => {
              this.state.post = text;
            }}
            defaultValue={this.state.post}
            autoFocus={true}
          />
        </ScrollView>
      </View>
    );
  }
}

Any ideas how to accomplish what I'm looking for?

Upvotes: 2

Views: 862

Answers (2)

Someone Special
Someone Special

Reputation: 13588

Kinda like a hack but i use the global variable method where we assign this to a variable call foo. Works for me.

let foo;

class App extends Component {

  static navigationOptions = ({ navigation }) => {
    return {
      title: 'Add Comment',
      headerRight: (
        <Button
          title='Post'
          onPress={() => foo.postComment() } <- Use foo instead of this
        />
      ),
    };
  };

componentWillMount() {
foo = this;
}
render() {

    return (<div>Don't be a foo</div>)
}
}

Upvotes: 0

Tieme
Tieme

Reputation: 65389

I see you've found the solution. For future readers:

Nonameolsson posted how to achieve this on Github:

In componentDidMount set the method as a param.

componentDidMount () {
  this.props.navigation.setParams({ postComment: this.postComment })
}

And use it in your navigationOptions:

static navigationOptions = ({ navigation }) => {
  const { params } = navigation.state
  return {
    title: 'Add Comment',
    headerRight: (
      <Button
        title='Post'
        onPress={() => params.postComment()}
      />
    ),
  };
};

Upvotes: 6

Related Questions