加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:54:27 所属栏目:百科 来源:网络整理
导读:我确实使用onPress“handler”呈现了以下类型的列表. 我已经意识到onPress处理程序是无用的,因为我无法获得按下的种族参考.我得到ref没有定义错误. var races = Engine.possibleRaces;function racePressed(ref) { console.log("REF: " + ref); // is never
我确实使用onPress“handler”呈现了以下类型的列表.

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

var races = Engine.possibleRaces;

function racePressed(ref) {
    console.log("REF: " + ref); // is never called
}

var races = Engine.possibleRaces;
var rowViews = [];
for (var i = 0; i < races.length; i++) {
  rowViews.push(
    <Text
      ref={i}
      onPress={() => racePressed(ref)} // ref is not defined
      style={styles.raceText}>{races[i].text}
    </Text>

  );
}

<View style={{width: Screen.width,flexDirection:'row',flexWrap: 'wrap',alignItems: "center"}}>
       {rowViews}
</View>

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

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

编辑:

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

'use strict';
import React,{
  AppRegistry,Component,StyleSheet,Text,View
} from 'react-native';

let texts = [{text: "Click wrapper text1"},{text: "Click wrapper text2"}];

class sandbox extends Component {

  rowPressed(ref,i) {
    console.log("rowPressed: " + ref + " " + i)
  }

  render() {

    var rows = [];

    for (var i = 0; i < texts.length; i++) {
      rows.push(
        <Text
          ref={i}
          onPress={() => this.rowPressed.bind(this,i)}
          style={styles.raceText}>{texts[i].text}
        </Text>
      );
    }

    return (
      <View style={styles.container}>

        <View>
          {rows}
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,justifyContent: 'center',alignItems: 'center'
  }
});

AppRegistry.registerComponent('sandbox',() => sandbox);

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

[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.
我建议你在构造函数中绑定该函数,如..
constructor(props){
    super(props);
    //your codes ....

    this.rowPressed = this.rowPressed.bind(this);
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读