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

时间:2017-06-28 18:15:12

标签: react-native react-navigation

我已制作了全屏TextInput,并且希望在按下Post button中的NavigationBar时执行操作。但是,因为我必须使用Button支持onPress支持静态方法的方法,所以我无法访问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>
    );
  }
}

任何想法如何实现我正在寻找的东西?

2 个答案:

答案 0 :(得分:6)

我看到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()}
      />
    ),
  };
};

答案 1 :(得分:0)

有点像黑客,但我使用全局变量方法,我们将其分配给变量调用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>)
}
}