【问题标题】:React Native undefined in not an objectReact Native undefined in not an object
【发布时间】:2015-07-31 00:15:12
【问题描述】:

我正在尝试从数组中生成一系列按钮。我有以下代码

render: function() {
    var locations = this.state.campus.map(function (item){
        var that = this;
        return(
            <TouchableHighlight style={styles.button}
                underlayColor='#dddddd'
                onPress={()=>this.buttonPress("this")}>
                <Text style={styles.buttonText}>{item}</Text>
            </TouchableHighlight>
        )
    });

    return (
        <View style={styles.container}>
            <Text style={styles.welcome}>Campus</Text>
            <View style={styles.flowDown}>
                {locations}
            </View>
            <TouchableHighlight style={styles.button}
                underlayColor='#dddddd'
                onPress={()=>this.buttonPress("this")}>
                <Text style={styles.buttonText}>'Hello'</Text>
            </TouchableHighlight>

        </View>
    );
}

这可以很好地呈现并且底部的按钮可以完美地工作。但是,地图功能中生成的按钮在按下时会产生错误。我已经尝试了 that = this 并使用了 bind(this)/bind(that) 但我仍然收到错误。

这样可以生成按钮吗?我不想使用 ListView,因为它会生成自己的全屏显示。

【问题讨论】:

标签: reactjs react-native


【解决方案1】:

试试这个:

render: function() {
    var that = this;
    var locations = this.state.campus.map(function (item){
        return(
            <TouchableHighlight style={styles.button}
                underlayColor='#dddddd'
                onPress={()=>that.buttonPress("this")}>
                <Text style={styles.buttonText}>{item}</Text>
            </TouchableHighlight>
        )
    });

    return (
        <View style={styles.container}>
            <Text style={styles.welcome}>Campus</Text>
            <View style={styles.flowDown}>
                {locations}
            </View>
            <TouchableHighlight style={styles.button}
                underlayColor='#dddddd'
                onPress={()=>this.buttonPress("this")}>
                <Text style={styles.buttonText}>'Hello'</Text>
            </TouchableHighlight>

        </View>
    );
}

【讨论】:

  • 谢谢,确实有效。我也明白为什么它会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多