【问题标题】:How to pass a component reference to onPress callback?如何将组件引用传递给 onPress 回调?
【发布时间】:2016-06-10 08:33:40
【问题描述】:

我确实使用 onPress "handler" 渲染了以下类型的列表。

我已经意识到 onPress 处理程序是无用的,因为我无法获得按下种族的引用。我得到 ref is not defined 错误。

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.

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我建议你在构造函数中绑定那个函数,比如..

    constructor(props){
        super(props);
        //your codes ....
    
        this.rowPressed = this.rowPressed.bind(this);
    }
    

    这将按照您的预期绑定 rowPressed 函数的 this 上下文,从而使您的代码正常工作。

    此外,要消除警告消息,您应该为每个 &lt;Text&gt; 元素提供唯一的 key 属性,在您的代码中使用 &lt;Text key={i} ....&gt; 应该可以工作。

    【讨论】:

    • 你能分享更多代码吗?我应该如何将以下代码更改为对“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={() =&gt; rowPressed(i)}
    【解决方案2】:

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

    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>
        );
    }
    

    干杯

    【讨论】:

    • 我不能在“this.rowPressed(i)”中使用“this”表达式,否则我会得到“无法读取未定义的属性 'rowPressed'”。我只需要使用 rowPressed 并正确调用函数。现在我对 rowPressed 函数有疑问。我无法再访问 this.state 了。 function rowPressed(id) { this.state... // Cannot read property 'state' of undefined }
    • 以下似乎有效,但由于某种原因感觉没有正确完成。 var that = this; function rowPressed(id) { that.state.races[id].chosen = !that.state.races[id].chosen;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2016-11-30
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多