首页 > 解决方案 > 如何在运行时将视图添加到本机反应中?

问题描述

我真的很困惑如何在运行时添加(和删除)视图和其他此类组件,
例如在您可以使用的 vanilla JavaScript 中document.querySelector('query-here').appendChild(element);

但是我如何使用本机反应来实现同样的目标?例如:

<Pressable onPress={()=>{addElement(element)}}>
<View>
 //add elements here
</View>

我知道如何直接实现它:

<View>
 {
  [...Array(23)].map((el, index) => {
    return(
     <View key={index}>
        <Text>added new element</Text>
     </View>
   )});
 }
</View>

有人可以指出我正确的方向吗?

标签: javascriptreact-native

解决方案


@cakelover 在这里如何根据组件的状态添加项目和删除项目。

import { Button } from 'react-native';


const [loader, setLoader] = React.useState(false); //donot show loader at initial
    const showLoader = isShowLoader => { // based on this function you can add or remove single loader from UI
       setLoader(isShowLoader);
    }
    return (
       <View>
         {loader && <LoaderComponent/>}
         <Button
           onPress={() => setLoader(!loader)}
           title="Toggle Loader Component"
           color="#841584"
         />
       </View>
     )

如果要添加或删除多个相同的组件,例如列表,则应为此使用项目数组。


推荐阅读