反应原生导航 - 使用组件状态的操作

Tho*_*mas 2 react-native react-navigation

我做了一个全屏幕,TextInput并希望Post buttonNavigationBar按下时执行动作.但是,因为我必须使ButtononPressprop中调用静态方法的方法,所以我无法访问state.

这是我当前的代码,状态是未定义的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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

任何想法如何完成我正在寻找的东西?

Tie*_*eme 6

我看到你找到了解决方案.对于未来的读者:

Nonameolsson在Github上发布了如何实现这一目标:

componentDidMount设定的方法作为PARAM.

componentDidMount () {
  this.props.navigation.setParams({ postComment: this.postComment })
}
Run Code Online (Sandbox Code Playgroud)

并在你的使用中navigationOptions:

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