首页 > 解决方案 > 如果导航参数中未定义值,如何添加按钮?

问题描述

我目前有这样的功能:

renderHeader = () => {
    return (
      <Text style={styles.headerStyle}>Let's configure to begin...</Text>
    );
  }

我想这样做,如果定义了参数(即如果存在某个值),那么下面有一个按钮,所以我尝试了:

renderHeader = () => {
    return (
      <Text style={styles.headerStyle}>Let's configure to begin...</Text>
      if(this.props.navigation.params.hasValue !== 'undefined'){
        <Button />
      }
    );
  }

但是,我知道Unexpected token, expected "," (54:6)我是否缺少能够进行条件渲染的东西?

标签: javascriptreact-native

解决方案


您没有正确使用 jsx,这就是为什么您会收到有关意外令牌的错误消息。有条件地插入元素的常用方法如下:

renderHeader = () => {
  return (
    <Text style={styles.headerStyle}>Let's configure to begin...</Text>
    {this.props.navigation.params.hasValue !== 'undefined' &&
      <Button />
    }
  );
}

或更笼统地说:

{ someCondition &&
  <ElementToInsertIfSomeCondition />
}

因为复合条件短路,如果someCondition为假,则条件返回假并且没有元素,否则条件的评估移到右侧并返回您的元素。


推荐阅读