项目映射时获取键和项目 onPress TouchableOpacity
Posted
技术标签:
【中文标题】项目映射时获取键和项目 onPress TouchableOpacity【英文标题】:Get key and item onPress TouchableOpacity when items are map 【发布时间】:2019-01-11 00:57:35 【问题描述】:在下面的代码中,项目已正确呈现并正常工作 但是当我按下 TouchableOpacity 时,它会返回事件。 我使用 JSON.stringify(event.nativeEvent) 但不工作
我想获取在 TouchableOpacity 上设置的 key value 和那个 item Data。
export default class MyLanguages extends Component
constructor(props)
super(props);
this.state =
languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
;
render()
return (
<View style=styles.container>
this.state.languageData.map( (item,index) =>
return (
<TouchableOpacity key=index
onPress= (event)=>
alert(event.nativeEvent)
>
<Text style=MyStyle.appFontStyle2>item</Text>
</TouchableOpacity>
)
)
</View>
)
【问题讨论】:
【参考方案1】:item
和index
还在onPress
回调的范围内,可以直接参考:
this.state.languageData.map((item, index) =>
return (
<TouchableOpacity
key=index
onPress=event =>
alert(`$index: $item`);
>
<Text style=MyStyle.appFontStyle2>item</Text>
</TouchableOpacity>
);
)
【讨论】:
它给出错误 未处理的 JS 异常:找不到变量:key @BhaumikSurani 抱歉,错字 - 应该是index
。【参考方案2】:
您也可以为此使用柯里化函数:
export default class MyLanguages extends Component
constructor(props)
super(props);
this.state =
languageData: ["English","Hindi","Tamil","Telugu","Gujarati","Marathi","Panjabi"],
;
// Curried function (A function which, when invoked (with an argument), returns another function that depends on the argument
onPressHandler = key => event =>
console.log(key, event)
render()
return (
<View style=styles.container>
this.state.languageData.map( (item,index) =>
// Invoke the curried function with the index as the argument for the key paremeter,
// which returns another function which is set as the onPress event handler
return (
<TouchableOpacity
key=index
onPress = this.onPressHandler(index)
>
<Text style=MyStyle.appFontStyle2>item</Text>
</TouchableOpacity>
)
)
</View>
)
【讨论】:
以上是关于项目映射时获取键和项目 onPress TouchableOpacity的主要内容,如果未能解决你的问题,请参考以下文章
React Native TouchableOpacity OnPress 不使用循环