【问题标题】:React-native/react-navigation: how do I access a component's state from `static navigationOptions`?React-native/react-navigation:如何从“静态导航选项”访问组件的状态?
【发布时间】:2017-09-10 00:59:38
【问题描述】:

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

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

【问题讨论】:

  • 你能做 console.log(this.constructor.name) 而不是在完成的新闻上提交吗?确保您有正确的上下文

标签: reactjs react-native react-navigation


【解决方案1】:

简单的设计模式

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

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

【讨论】:

    【解决方案2】:

    使用setParams 发送绑定函数,然后您将可以在该函数中访问组件的state

    例子:

    constructor(props) {
        super(props);
        this._handleButtonNext = this._handleButtonNext.bind(this);
        this.state = { selectedIndex: 0 }
    }
    
    componentDidMount() {
        this.props.navigation.setParams({
            handleButtonNext: this._handleButtonNext,
        });
    }
    
    _handleButtonNext() {
        let action = NavigationActions.setParams({
            params: { selectedImage: images[this.state.selectedIndex] }
        });
        this.props.navigation.dispatch(action);
    }
    

    现在您可以拥有与组件的state 相关的按钮处理程序。

    static navigationOptions = ({ navigation }) => {
        const { state, setParams, navigate } = navigation;
        const params = state.params || {};
    
        return {
            headerTitleStyle: { alignSelf: 'center' },
            title: 'Select An Icon',
            headerRight: <Button title='Next' onPress={params.handleButtonNext} />
        }
    }
    

    【讨论】:

    • 谢谢你。这确实应该包含在 react-navigation 的文档中。我个人认为 React Native 通过弃用导航来支持这个库是有害的。现在还很早,感觉大面积破碎。
    • 这比在参数中设置整个组件效果更好,这会产生像 Object cannot be child 这样的错误。
    【解决方案3】:

    在你的componentDidMount上,你可以使用

    this.navigation.setParams({
     myTitle: this.props.myTitle
    })
    

    然后,将函数传递给静态道具上的标题。这个函数可以访问你之前设置的参数

    感谢rafaelcorreiapoli

    【讨论】:

      【解决方案4】:

      您收到此错误是因为您在声明 constructor() 之前使用了道具和状态。与构造函数一样,我们首先调用 super(props) 以便我们可以在组件中使用 props。请执行以下操作以获得所需的结果。

      constructor(props) {
          super(props);
          this.state = {
            formText: ''
          };
      
        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',
        }
        }
      

      干杯:)

      【讨论】:

      • static 不能在构造函数中使用。里面的道具(导航相关的道具)由react-navigation提供。
      • 另外,navigationOptions 的声明是 react-navigation 所必需的
      • 哎呀我错误地将navigationOptions放在了constructor()中......我的错:)
      • 在构造函数之后移动 naviagtionOptions 然后它会起作用:)
      • 你不关注。该错误根本与状态或道具无关,并且在构造函数后移动它没有帮助
      猜你喜欢
      • 2018-03-07
      • 2021-12-01
      • 2018-09-25
      • 2017-07-11
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多