三元操作符

问题描述 投票:0回答:1

是否可以在内置组件标签中使用三元操作符?例如,我正在使用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导航适用于所有Items,无论使用的是什么标题或面孔。我想引入一个有条件的导航。例如,如果

title == 'news'

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

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

但这显然是行不通的 我得到的是 '...' expected.关于 title.

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

Cannot find name 'setShowAddFriendPage'.
javascript reactjs typescript react-native native-base
1个回答
2
投票

你可以这样做

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

1
投票

使用 useCallback 以创建 onPress 函数,根据你的条件有不同的行为。

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

它依赖于 title所以它将被重新创建,并且只有在以下情况下才会重新渲染该组件 title 变化。

那么就可以这样使用。

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

0
投票

你可以使用 spread 操作符 (...) 来有条件地添加道具到组件中。

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

这样组件就会有 onPress 当标题等于 'news'

© www.soinside.com 2019 - 2024. All rights reserved.