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>@H_301_6@
  23. 我也尝试将i作为参数传递.它不起作用,因为它在迭代结束后具有值.基本上它有races.length值.

  24. onPress={() => racePressed(i)} // Same as races.length@H_301_6@ 
  25.  

    编辑:

  26.  

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

  27.   
  28.  
    'use strict';
  29. import React,{
  30.   AppRegistry,Component,StyleSheet,Text,View
  31. } from 'react-native';
  32. let texts = [{text: "Click wrapper text1"},{text: "Click wrapper text2"}];
  33. class sandBox extends Component {
  34.   rowPressed(ref,i) {
  35.     console.log("rowPressed: " + ref + " " + i)
  36.   }
  37.   render() {
  38.     var rows = [];
  39.     for (var i = 0; i < texts.length; i++) {
  40.       rows.push(
  41.         <Text
  42.           ref={i}
  43.           onPress={() => this.rowPressed.bind(this,i)}
  44.           style={styles.raceText}>{texts[i].text}
  45.         </Text>
  46.       );
  47.     }
  48.     return (
  49.       <View style={styles.container}>
  50.         <View>
  51.           {rows}
  52.         </View>
  53.       </View>
  54.     );
  55.   }
  56. }
  57. const styles = StyleSheet.create({
  58.   container: {
  59.     flex: 1,justifyContent: 'center',alignItems: 'center'
  60.   }
  61. });
  62. AppRegistry.registerComponent('sandBox',() => sandBox);@H_301_6@ 
  63.  

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

  64.   
  65.  
    [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.@H_301_6@
我建议你在构造函数中绑定该函数,如..
  1. constructor(props){
  2. super(props);
  3. //your codes ....
  4.  
  5. this.rowPressed = this.rowPressed.bind(this);
  6. }@H_301_6@
  7. 这会像你期望的那样绑定rowPressed函数的这个上下文,使你的代码正常工作.

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

猜你在找的React相关文章