繁体   English   中英

使用 react-native-component 时 onChangeText 的问题 this.setState 没有在 onChangeText 内设置 state

[英]Problem with onChangeText whenn using react-native-component this.setState doesnt set state inside onChangeText

我对本机反应有疑问,并且有点坚持为什么这不起作用。 我正在尝试使用 react-native-elements 中输入组件的 onChangeText 属性更新我的 state 朋友页面。

export default class FriendsPage extends Component {
    
    constructor(props) {
        super(props);
        this.state = {
            search:'',
            loading:false
        };
    }
    findFriend(){
        //Does stuff
    }
  
    renderButtonOrLoading() {
        if(this.state.loading){
            return <Text>Loading</Text>
        }
        return(
            <View style={styles.container}>
                <Button title = "Search" onPress={()=>this.findFriend()} styles={styles.button}/>
            </View>
        );
    }
    render(){
      console.log(this.search)
        return(
            <View style={styles.container}>
              <TextInput style={styles.input}
                  placeholder='username'
                  onChangeText={search =>this.setState({ search})}/>
                     
              {this.renderButtonOrLoading()}
            </View>

        
        );
    }
}

const styles = StyleSheet.create({
    container:{
        marginTop: 100,
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',

    }
});

我的问题是,每次我调用 function findFriends() 时,都会收到一个错误,指出 this.search 未定义。 我试图在渲染期间控制台记录 this.search ,但它似乎在每个渲染周期都保持未定义。 我有一种感觉,我应该以某种方式使用道具,但我不确定,因为我对反应比较陌生。

编辑:感谢所有答案,我试图调用 this.search 虽然它应该是 this.state.search 这就是破坏我的代码的原因。

目前尚不清楚变量search是否与 state 中的相同。 如果是,则此代码将不起作用。

onChangeText={search =>this.setState({ search})} // setting a state to itself won't work

如果它是一个单独的变量,那么您错误地调用了setState 我建议更改变量的名称。 setState 调用应该更像这样:

onChangeText={ s => this.setState( { search: s } );

search未定义(错误),因为您在 state 中将其设置为“”。 对于基于类的 React 方法,您可以使用 getDerivedStateFromProps() 方法(如果您从道具传递搜索词)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM