RN新手求助:在写一个搜索的组件时报错 “null is not an object(evaluating 'this.state.value')”



  • 我的代码如下:
    import React, { Component } from 'react';
    import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TextInput,
    PixelRatio
    } from 'react-native';

    var onePT = 1 / PixelRatio.get();

    class Search extends Component {
    getInitialState () {
    return {
    show: false
    };
    }

    getValue (text) {
    var value = text ;
    this.setState({
    show: true,
    value: value
    });
    }

    hide (val) {
    this.setState({
    show: false,
    value: val
    });
    }

    render (){
    return (
    <View style={styles.flex}>
    <View style={[styles.flexDirection, styles.inputHeight]}>
    <View style={styles.flex}>
    <TextInput
    style={styles.input}
    returnKeyType="search"
    placeholder="请输入关键字"
    onEndEditing={this.hide.bind(this, this.state.value)}
    value={this.state.value}
    onChangeText={this.getValue}/>
    </View>
    <View style={styles.btn}>
    <Text style={styles.search} onPress={this.hide.bind(this, this.state.value)}>搜索</Text>
    </View>
    </View>
    {this.state.show?
    <View style={[styles.result]}>
    <Text onPress={this.hide.bind(this, this.state.value + '庄')}
    style={styles.item} numberOfLines={1}>{this.state.value}庄</Text>
    <Text onPress={this.hide.bind(this, this.state.value + '园街')}
    style={styles.item} numberOfLines={1}>{this.state.value}园街</Text>
    <Text onPress={this.hide.bind(this, 80 + this.state.value + '综合商店')}
    style={styles.item} numberOfLines={1}>80{this.state.value}综合商店</Text>
    <Text onPress={this.hide.bind(this, this.state.value + '桃')}
    style={styles.item} numberOfLines={1}>{this.state.value}桃</Text>
    <Text onPress={this.hide.bind(this, '杨林' + this.state.value + '园')}
    style={styles.item} numberOfLines={1}>杨林{this.state.value}</Text>
    </View>
    : null
    }
    </View>
    );
    }
    }

    class inputExample extends Component {
    render () {
    return (
    <View style={[styles.flex, styles.topStatus]}>
    <Search></Search>
    </View>
    )
    }
    }

    const styles = StyleSheet.create({
    //这里省略
    });

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

    显示50行 onEndEditing={this.hide.bind(this, this.state.value)} 这里有问题。



  • 自己已经解决
    在react native 应用ES6 的时候初始化state应该用在constructor内而不应该用getInitialState()