React-native/react-navigation:如何从“静态导航选项"访问组件的状态? [英] React-native/react-navigation: how do I access a component's state from `static navigationOptions`?

查看:27
本文介绍了React-native/react-navigation:如何从“静态导航选项"访问组件的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个表单组件,并且需要使用导航栏中的按钮提交组件状态的一部分,您如何处理?

How do you handle cases when you have, say, a form component, and you need to submit a part of the component's state using button in navigation bar?

const navBtn = (iconName, onPress) => (
  <TouchableOpacity
    onPress={onPress}
    style={styles.iconWrapper}
  >
    <Icon name={iconName} size={cs.iconSize} style={styles.icon} />
  </TouchableOpacity>
)

class ComponentName extends Component {

  static navigationOptions = {
    header: (props) => ({
      tintColor: 'white',
      style: {
        backgroundColor: cs.primaryColor
      },
      left: navBtn('clear', () => props.goBack()),
      right: navBtn('done', () => this.submitForm()), // error: this.submitForm is not a function
    }),
    title: 'Form',
  }

  constructor(props) {
    super(props);
    this.state = {
      formText: ''
    };
  }

  submitForm() {
    this.props.submitFormAction(this.state.formText)
  }

  render() {
    return (
      <View>
        ...form goes here
      </View>
    );
  }
}

推荐答案

简单的设计模式

作为@val 出色答案的后续行动,以下是我构建组件的方式,以便在 componentWillMount 中设置所有参数.我发现这使它更简单,并且是所有其他屏幕都可以遵循的简单模式.

Simple Design Pattern

Just as a follow-up to @val's excellent answer, here's how I structured my Component so that all the params are set in the componentWillMount. I find this keeps it simpler and is an easy pattern to follow for all other screens.

static navigationOptions = ({navigation, screenProps}) => {
  const params = navigation.state.params || {};

  return {
    title:       params.title,
    headerLeft:  params.headerLeft,
    headerRight: params.headerRight,
  }
}

_setNavigationParams() {
  let title       = 'Form';
  let headerLeft  = <Button onPress={this._clearForm.bind(this)} />;
  let headerRight = <Button onPress={this._submitForm.bind(this)} />;

  this.props.navigation.setParams({ 
    title,
    headerLeft,
    headerRight, 
  });
}

componentWillMount() {
  this._setNavigationParams();
}

_clearForm() {
  // Clear form code...
}

_submitForm() {
  // Submit form code...
}

这篇关于React-native/react-navigation:如何从“静态导航选项"访问组件的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆