react-native – 如何将组件引用传递给onPress回调?

前端之家收集整理的这篇文章主要介绍了react-native – 如何将组件引用传递给onPress回调?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我确实使用onPress“handler”呈现了以下类型的列表.

我已经意识到onPress处理程序是无用的,因为我无法获得按下的种族参考.我得到ref没有定义错误.

  1. var races = Engine.possibleRaces;
  2.  
  3. function racePressed(ref) {
  4. console.log("REF: " + ref); // is never called
  5. }
  6.  
  7. var races = Engine.possibleRaces;
  8. var rowViews = [];
  9. for (var i = 0; i < races.length; i++) {
  10. rowViews.push(
  11. <Text
  12. ref={i}
  13. onPress={() => racePressed(ref)} // ref is not defined
  14. style={styles.raceText}>{races[i].text}
  15. </Text>
  16.  
  17. );
  18. }
  19.  
  20. <View style={{width: Screen.width,flexDirection:'row',flexWrap: 'wrap',alignItems: "center"}}>
  21. {rowViews}
  22. </View>

我也尝试将i作为参数传递.它不起作用,因为它在迭代结束后具有值.基本上它有races.length值.

  1. onPress={() => racePressed(i)} // Same as races.length

编辑:

我确实将问题隔离到以下程序.

  1. 'use strict';
  2. import React,{
  3. AppRegistry,Component,StyleSheet,Text,View
  4. } from 'react-native';
  5.  
  6. let texts = [{text: "Click wrapper text1"},{text: "Click wrapper text2"}];
  7.  
  8. class sandBox extends Component {
  9.  
  10. rowPressed(ref,i) {
  11. console.log("rowPressed: " + ref + " " + i)
  12. }
  13.  
  14. render() {
  15.  
  16. var rows = [];
  17.  
  18. for (var i = 0; i < texts.length; i++) {
  19. rows.push(
  20. <Text
  21. ref={i}
  22. onPress={() => this.rowPressed.bind(this,i)}
  23. style={styles.raceText}>{texts[i].text}
  24. </Text>
  25. );
  26. }
  27.  
  28. return (
  29. <View style={styles.container}>
  30.  
  31. <View>
  32. {rows}
  33. </View>
  34.  
  35. </View>
  36. );
  37. }
  38. }
  39.  
  40. const styles = StyleSheet.create({
  41. container: {
  42. flex: 1,justifyContent: 'center',alignItems: 'center'
  43. }
  44. });
  45.  
  46. AppRegistry.registerComponent('sandBox',() => sandBox);

除非跟随警告,否则不会调用回调并且不会抛出任何错误

  1. [tid:com.facebook.React.JavaScript] Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `sandBox`. See https://fb.me/react-warning-keys for more information.
我建议你在构造函数中绑定该函数,如..
  1. constructor(props){
  2. super(props);
  3. //your codes ....
  4.  
  5. this.rowPressed = this.rowPressed.bind(this);
  6. }

这会像你期望的那样绑定rowPressed函数的这个上下文,使你的代码正常工作.

另外,要删除警告消息,您应为每个< Text>提供唯一的键属性.元素,使用< Text key = {i} ....>在你的代码应该工作.

猜你在找的React相关文章