react-native:如何呈现状态

时间:2019-07-17 04:34:36

标签: javascript react-native

我在渲染state时遇到问题。我的状态的初始值为empty,但是当我按下按钮state change时。

我希望立即看到此更改,但是当开始在我的state中键入内容时,只有renders Textinput

这是我的状态:

  constructor(props) {
    super(props)
    this.state = {
      noteText: '',
      userName:'',
  }
}

我使用onPress按钮更改状态

changeState(){
this.setState({userName:'Kevin'})
}

这是我呈现状态的地方

    <View>
//I want to immediately render this.state.userName
       <Text>{this.state.userName}</Text>
          <TextInput
                    onChangeText={(noteText) => this.setState({noteText:noteText})}
                    value={this.state.noteText}
                    />
    </View>

直到开始在TextInput中键入内容时,我的状态才会呈现。知道我如何立即渲染吗?

3 个答案:

答案 0 :(得分:3)

您在这里有两种方式。

设置默认状态

constructor(props) {
    super(props)
    this.state = {
      noteText: '',
      userName:'Kevin',
  }
  this.changeState = this.changeState.bind(this);
}

或在changeState中致电componentDidMount

componentDidMount(){
   this.changeState(); //bind this to changeState in constructor
}

答案 1 :(得分:3)

您宁可在内部构造函数中使用内部绑定函数,也可以使用箭头函数。

constructor(props) {
  this.changeState = this.changeState.bind(this);
}

changeState = () => {
  this.setState({ userName: "Kevin" });
};

检查简单的小吃:https://snack.expo.io/@abranhe/change-state

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default class App extends Component {
  state = { userName: '' };

  changeState = userName => {
    this.setState({ userName });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.username}>{this.state.userName}</Text>
        <Button title="Abraham" onPress={() => this.changeState('Abraham')} />
        <Button title="James" onPress={() => this.changeState('James')} />
        <Button title="Mark" onPress={() => this.changeState('Mark')} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  username: {
    alignSelf: 'center',
    marginBottom: 20,
  },
});

答案 2 :(得分:-1)

 changeState(text){
   this.setState({userName:text , noteText:text} )
 }


 <TextInput
   onChangeText={(noteText) => this.changeState(noteText)}
   value={this.state.noteText}
   />