React Native组件在移除某些子组件时无法正确呈现

kpbpu008  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(72)

我想允许用户通过设置一个布尔状态(我称之为pinyinMode)来切换Text组件是否存在。

return (
    <View style={{ backgroundColor: 'red' }}>
      <Pressable style={{ alignItems: 'center', justifyContent: 'center', backgroundColor: 'green' }}>
        <Text style={{ fontSize: 20, backgroundColor: 'blue' }}>{hanzi}</Text>
        {pinyinMode && <Text style={{ backgroundColor: 'yellow' }}>{pinyin}</Text>}
      </Pressable>
    </View>
);

字符串
参考下面的屏幕截图,当pinyinModefalse时,View不会围绕其子对象调整大小。(我还将()字符的fontSize: 32减小为fontSize: 20。)
pinyinMode == true


的数据
pinyinMode == false



如果删除{pinyinMode && <Text style={{ backgroundColor: 'green' }}>{pinyin}</Text>}行,View将正确呈现:

return (
    <View style={{ backgroundColor: 'red' }}>
      <Pressable style={{ alignItems: 'center', justifyContent: 'center', backgroundColor: 'green' }}>
        <Text style={{ fontSize: 20, backgroundColor: 'blue' }}>{hanzi}</Text>
      </Pressable>
    </View>
);



如何让View正确调整其子节点周围的大小?

ccgok5k5

ccgok5k51#

我使用的解决方案是创建两个单独的组件,一个包含pinyinText组件,另一个不包含pinyinText组件。当pinyinMode为true时返回第一个组件,当pinyinMode为false时返回第二个组件。

相关问题