组件标签内的三元运算符

ternary operator inside a component tag

是否可以在 built-in 组件标签中使用三元运算符?例如,我正在使用来自 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)onPress

Cannot find name 'setShowAddFriendPage'.

你可以这样做

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

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

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

只要标题等于 'news'

,组件就会有 onPress 属性

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

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

它依赖于title,所以它会被重新创建,只有当title改变时才会重新渲染组件。

然后这样使用它:

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