【问题标题】:ternary operator inside a component tag组件标签内的三元运算符
【发布时间】:2020-08-24 14:13:04
【问题描述】:

是否可以在内置组件标签中使用三元运算符?例如,我正在使用来自 React Native(Native Base)的 Touchable Opacity:

type ItemProps = {
  title: string;
  face: string;
};

export const Item: React.FunctionComponent<ItemProps> = ({
  title,
  face,
}) => {

  const [showAddFriendPage, setShowAddFriendPage] = useState(false);

  const toggleAddFriendPage = () => {
    setShowAddFriendPage(showAddFriendPage ? false : true);
  };

  return (
    <TouchableOpacity activeOpacity={0.8}
    onPress={() =>
      setShowAddFriendPage(true)
    }   >
      <View>
        <Thumbnail small source={{ uri: face }} style={styles.thumbnail} />
        <Text numberOfLines={1} style={styles.title}>
          {title}
        </Text>
        <AddFriendPage
          showAddFriendPage={showAddFriendPage}
          toggleShowPage={toggleAddFriendPage}
        />
      </View>
    </TouchableOpacity>
  );
};

目前,无论使用什么标题或头像,onPress 导航都适用于所有项目。我想介绍一个条件导航。例如,如果

title == 'news'

然后onPress...。由于我们不能在 jsx 中使用 if else 语句,所以我尝试了三元运算符:

 <TouchableOpacity activeOpacity={0.8}
 {title == 'news'? {
      onPress={() =>
      setShowAddFriendPage(true)
    }   
    } }
/>

但这显然行不通。我在title 上得到'...' expected.

No value exists in scope for the shorthand property 'onPress'. Either declare one or provide an initializer.ts(18004)on onPressand

Cannot find name 'setShowAddFriendPage'.

【问题讨论】:

    标签: javascript reactjs typescript react-native native-base


    【解决方案1】:

    你可以这样做

             <TouchableOpacity activeOpacity={0.8}
                  onPress={() =>{
                   if(title == 'news'){
                    setShowAddFriendPage(true)
                    }
              }}   
              />
    

    【讨论】:

      【解决方案2】:

      使用useCallback 创建一个onPress 函数,该函数根据您的条件具有不同的行为。

      const onPress = useCallback(() => {
        if (title === 'news') {
          setShowAddFriendPage(true)
        }
      }, [title])
      

      它依赖于title,所以它会被重新创建,并且组件只有在title发生变化时才会重新渲染。

      然后这样使用它:

      <TouchableOpacity activeOpacity={0.8} onPress={onPress}>
        {/* … */}
      </TouchableOpacity>
      

      【讨论】:

        【解决方案3】:

        您可以使用扩展运算符 (...) 有条件地向组件添加道具。

        <TouchableOpacity
            activeOpacity={0.8}
            {...(title == 'news' && { onPress: () => setShowAddFriendPage(true) })}
        />
        

        只要标题等于'news',这种方式组件就会有onPress 属性

        【讨论】:

        • @BertrandMarron 你的意思是它不干净吗?
        猜你喜欢
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 2019-11-19
        • 2021-08-24
        • 2019-01-03
        • 2018-07-13
        • 2014-01-28
        • 1970-01-01
        相关资源
        最近更新 更多