【问题标题】:react native passing onPress with value将传递 onPress 的本机反应与值
【发布时间】:2021-05-30 15:59:18
【问题描述】:

我有一个父组件,它创建一个将“onPress”传递给父组件的子组件,

工作正常,但现在需要将一些值从子级传递给父级...

父组件:

const filterBarTapped = ( index:any )=> {
  console.log('tongo:', index )

}

const Charter = ({ isSingle, isDarkMode, data1, data2 }: Charterprops) => {

  return (
    <View>
      { Object.keys(data1).length > 6 && <TabBar data={data1} onPress={() => filterBarTapped()}/>} ...

孩子:

const handleClick = (index:any) => {
    setSelectedTab(index)
    console.log("sale index:", index)
     onPress()

}

return (
        <View style={{
            flexDirection: "row",
            justifyContent: 'space-around',
            alignItems: 'center',
        }}>


            {tabs.map(p => (

                <Tab
                    title={p.title}
                    onPress={() => handleClick(p.itemIndex)}
                    itemIndex={p.itemIndex}
                    selectedItem={selectedTab} />
            ))}

        </View>
    )
}

但我明白了,

汤戈:未定义

那么,如何将索引传递给我的 onPress 的父级?

干杯

【问题讨论】:

    标签: reactjs react-native onpress


    【解决方案1】:

    您需要将值传递给 onPress 回调

    孩子

    onPress(index)
    

    然后在过滤函数中更新它

    onPress={(index) => filterBarTapped(index)}
    

    为了在filterBarTapped函数上可以访问

    快捷方式:

    由于onPressfilterBarTapped 的args 数量相同,您可以编写:

    onPress={filterBarTapped}
    

    在父组件上

    【讨论】:

      【解决方案2】:

      代替

      filterBarTapped()}/>}

      可以直接传递filterBarTapped函数

      <TabBar data={data1} onPress={filterBarTapped}/>}
      

      这样,从onPresss 事件传递的任何值都将可用于filterBarTapped 函数。并且代码变得更易于维护。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多