【问题标题】:Expo React Native - Json.map() - Dynamic Data ClickableExpo React Native - Json.map() - 可点击的动态数据
【发布时间】:2021-12-25 17:59:20
【问题描述】:

我正在开发一个 React Native 应用程序,我希望仅在单击另一个元素时才显示部分元素。

我使用const [showSlide, setShowSlide] = useState(false); 实现了这一点,然后使用{showSlide ? (<View>Element</View>): null} 之类的条件显示

它在我的静态演示中效果很好,但我希望使用 json.map() 函数获得相同的结果。

我不知道如何对我想在地图功能中隐藏/显示的想法进行唯一引用。

我在这里做了一个演示来展示我的动态数据和静态数据作为我想要做的参考:https://snack.expo.dev/@37creaorganization/json-data---clickable

export default function App() {

  const [showSlide, setShowSlide] = useState(false);

  return (
    <View style={styles.container}>
    {/* STATIC EXAMPLE */}
    <TouchableOpacity onPress={() => {setShowSlide(!showSlide)}}>
      <Text style={styles.paragraph}>
        {dataC.customer[0].name}   
      </Text>
      {showSlide ? (
        <View>
          <Text>{dataC.customer[0].requests[0].title}</Text>
        </View>
      ) : null}
    </TouchableOpacity>
    {/* END OF STATIC EXAMPLE */}
    <View style={{width:"100%", height:5, backgroundColor:"red", marginTop: 10, marginBottom: 10}}></View>
    <Text style={{textAlign: "center"}}>DYNAMIC EXAMPLE</Text>
    {/* DYNAMIC DATA */}
    { dataC.customer.map((customer)=>(
      <TouchableOpacity onPress={() => {setShowSlide(!showSlide)}}>
        <Text style={styles.paragraph}>
          {customer.name}   
        </Text>
          <View>
            <Text>{customer.requests[0].title} </Text>
          </View>
      </TouchableOpacity>
    ))}
    {/* END OF DYNAMIC DATA*/}
    </View>
  );
}

【问题讨论】:

  • 您的代码应该发布在此处,而不是某些外部网站。您已经在这个网站上工作了 六年,当然您应该知道这一点。
  • @Pointy 我会更新的。

标签: javascript json react-native function expo


【解决方案1】:

在 React 中分离组件始终是最佳实践

const Customer = ({customer, titleVisible=false, toggleVisible})=>{
  const onToggleVisible = ()=>toggleVisible && toggleVisible(customer.name);
  return (
      <TouchableOpacity onPress={onToggleVisible}>
        <Text style={styles.paragraph}>
          {customer.name}
        </Text>
        {titleVisible && <View>
          <Text>{customer.requests[0].title} </Text>
        </View>}
      </TouchableOpacity>
  )
}

上面的组件根据您的要求显示客户。

在您的App 组件中声明

const [show, setShow] = useState({});

这里我们将存储布尔值和标题名称。

切换可见功能看起来像

 const toggleVisible = (name)=>{
    if(show[name]){
      setShow({...show, [name]:false}) //Updating it to false as its already visible
    } else {
      setShow({...show, [name]:true}) //Its not visible so let's make it visible
    }
  }

您可以使用上面的客户组件,如下所示

{ dataC.customer.map((customer)=>(
      <Customer customer={customer} titleVisible={show[customer.name]} toggleVisible={toggleVisible}/>
    ))}

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多