【问题标题】:How to pass this.state value in custom navigationOptions on React-Native如何在 React-Native 上的自定义 navigationOptions 中传递 this.state 值
【发布时间】:2018-04-26 17:29:39
【问题描述】:

我是 React-Native 的新手,我正在尝试使用 React-Native Navigation 如何在我的自定义标头中传递值

这是我的组件 A 与 CustomHeader 的样子

constructor(props) {
    super(props);       
    this.state = {
      sortId: 4
    }
 }

componentDidMount() {
    this.props.navigation.setParams({
      sortId: this.state.sortId
    })
}

static navigationOptions = {
    header: props =>    // Your custom header
      <CustomHeader
         sortId={props.navigation.params.sortId}
      />
};

在我的 CustomHeader 组件中,当我尝试显示这样的值时

export default class CustomHeader extends Component {

  constructor(props) {
   super(props);
  }

 componentWillMount() {
   Alert.alert(this.props.sortId.toString());
 }

它不工作,我收到错误:undefined is not an object (evaluating 'this.props.sortId')

但是当我像下面这样硬编码一个值时,它确实有效

static navigationOptions = {
    header: props =>    // Your custom header
      <CustomHeader
         sortId={4} //this works
      />
};

知道如何传递参数吗?我错过了什么?我不明白如何向props 添加参数并在navigationOptions 中访问它们。

【问题讨论】:

  • 能否添加完整的代码,因为很难确定要传递的状态是否在组件挂载之前定义?
  • 不工作是什么意思?你有错误吗?
  • 我已经更新了我的问题来回答你的两个 cmets

标签: react-native react-native-navigation


【解决方案1】:

如果你需要访问paramsnavigationOptions,那么你需要把你的代码改成

    static navigationOptions = {
    header: props =>    // Your custom header
      <CustomHeader
         sortId={props.navigation.state.params.sortId} //... state is missing
      />
};

如上所述here

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2017-10-26
    • 2018-10-24
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多