【问题标题】:React Native Navigation - Action using Component's StateReact Native Navigation - 使用组件状态的操作
【发布时间】:2017-06-28 18:15:12
【问题描述】:

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

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

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-02
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多