TouchableHighlight按错误

时间:2017-04-18 23:28:16

标签: react-native react-native-android

我是新生的反应本地人,我只是试图玩弄行动和状态。 我不知道这个组件中的问题所在。

我收到错误undefined is not an object (evaluating 'this.wrappedInstance.setNativeProps')

import React, { Component } from 'react';
import { Container, Text } from 'native-base';
import {
    AppRegistry,
    View,
    TouchableHighlight
} from 'react-native';

export default class Page2 extends Component {
    constructor(){
        super();
        this.state  = {
            mess: "Page 2 message"
        }
    }
    onPress(){
        this.state.mess = this.state.mess+" wow a click!"
    }
    render() {
        return (
            <View>
                <TouchableHighlight
                    onPress={this.onPress}
                    underlayColor="blue"
                >
                <Text> {this.state.mess}</Text>
                </TouchableHighlight>
            </View>
        );
    }
}
AppRegistry.registerComponent('Page2', () => Page2);

3 个答案:

答案 0 :(得分:1)

你永远不想改变状态,而是你想要使用setState。

 onPress(){
    this.state.mess = this.state.mess+" wow a click!" //mutating state
}

更改为:

onPress = () => { //arrow syntax will change the scope of `this` to your component
    this.setState(prevState => ({ mess: prevState.mess + " wow a click!" });
} // anytime you want to alter state based on previous state you should use this syntax

答案 1 :(得分:1)

首先,请听听Matt Aft的回答,因为这是您代码中的一个重大错误。

其次,您遇到的实际错误是Native Base和TouchableHighlights的问题。 See this bug。我从来没有使用Native Base,但我知道TouchableHighlights只能有一个子组件,而且看起来像bug一样,因为建议是将任何Native Base组件包装成一个TouchableHighlight的子组件视图。所以你的渲染代码应该是这样的:

render() {
    return (
        <View>
            <TouchableHighlight
                onPress={this.onPress}
                underlayColor="blue"
            >
                <View>
                    <Text> {this.state.mess}</Text>
                </View>
            </TouchableHighlight>
        </View>
    );
}

这是一个答案 - 如果你刚开始使用React Native,我建议不要使用你还没有完全理解的额外库(例如,Native Base),因为你可以运行在不了解事情如何运作的情况下,看似神秘且无法调试的错误。

答案 2 :(得分:1)

首先,Michael Cheng和Matt Aft的回答可能有所帮助,请试试。

其次,我有另一个建议(不是答案,只是建议:))。我偶尔会遇到另一个TouchableHighlight的错误(此时我无法提供错误消息)。在我的情况下,我使用TouchableOpacity而不是临时。

所以我建议您使用自定义组件(如XXXTouchble)并使其扩展为TouchableOpacity或TouchableHighlight,然后在您的代码中使用您自己的XXXTouchble。如果错误有一天得到修复,您无需修改​​所有文件,只需修改XXXTouchble。