React Native Navigation - 使用组件状态的动作

React Native Navigation - Action using Component's State

我制作了一个全屏 TextInput 并希望在按下 NavigationBar 中的 Post button 时执行一个操作。但是,因为我必须将 ButtononPress prop 中调用的方法设为静态方法,所以我无法访问 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>
    );
  }
}

有什么想法可以实现我正在寻找的东西吗?

我看到了 you've found 解决方案。对于未来的读者:

Nonameolsson 在 Github 上发布了如何实现此目的:

componentDidMount 中将方法设置为参数。

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

并在您的 navigationOptions 中使用它:

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

有点像黑客,但我使用全局变量方法,我们将其分配给变量调用 foo。适合我。

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>)
}
}