用值对本地传递 onPress 做出反应

问题描述

我有一个父组件,它创建一个将“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>
    )
}

但我明白了,

tongo:未定义

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

干杯

解决方法

您需要将值传递给 onPress 回调

孩子

onPress(index)

然后在过滤器函数中更新它

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

为了可以在 filterBarTapped 函数上访问

快捷方式:

由于 onPressfilterBarTapped 具有相同数量的参数,您可以只写:

onPress={filterBarTapped}

在父组件上

,

代替

filterBarTapped()}/>}

可以直接传递filterBarTapped函数

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

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