如何将组件引用传递给 onPress 回调函数?

7

我使用 onPress "handler" 渲染了下面这种列表:

enter image description here

我发现 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.
2个回答

12

我建议你像这样在构造函数中绑定那个函数:

我建议您将该功能绑定在构造函数中,例如..

constructor(props){
    super(props);
    //your codes ....

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

使用这个可以绑定rowPressed函数中的上下文,使你的代码正常工作。

此外,为了消除警告消息,您应该为每个<Text>元素提供一个唯一的key属性,在您的代码中使用<Text key={i} ....>应该可以解决问题。


你能分享更多的代码吗?我应该如何修改以下代码以访问“this”?render: function() { function rowPressed(id) { // Cannot read property 'state' of undefined this.state.races[id].chosen != this.state.races[id].chosen; } this.rowPressed = this.rowPressed.bind(this); ... onPress={() => rowPressed(i)} - Markku

3

我尝试做类似的事情,并找到了这个解决方案:

render() {
    var _data = texts;
    return (
        <View style={styles.container}>
        { _data.map(function(object,i) {
            return (
                <Text ref={i}
                  onPress={() => this.rowPressed(i)}
                  style={styles.raceText}>{texts[i].text}
                </Text> );
            })
        }
        </View>
    );
}

干杯


1
如果在“this.rowPressed(i)”中使用“this”表达式,会出现“Cannot read property 'rowPressed' of undefined”的错误。我只需要使用rowPressed,函数就可以正常调用了。现在我遇到了rowPressed函数的问题。我不能再访问this.state了。function rowPressed(id) { this.state... // Cannot read property 'state' of undefined } - Markku
以下代码似乎能够正常工作,但出于某种原因感觉完成得不太好。 var that = this; function rowPressed(id) { that.state.races[id].chosen = !that.state.races[id].chosen; - Markku

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接