【问题标题】:react-native : how to render statereact-native:如何渲染状态
【发布时间】:2019-11-25 20:35:30
【问题描述】:

我无法呈现我的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 中输入内容之前,我的状态不会呈现。知道如何立即渲染吗?

【问题讨论】:

  • 你可以在你的构造函数上做changeState=()=&gt;{}或this.changeState = this.changeState.bind(this)。

标签: javascript react-native


【解决方案1】:

这里有两种方法。

设置默认状态,

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

或者在componentDidMount中拨打changeState,

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

【讨论】:

    【解决方案2】:

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

    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,
      },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2021-07-12
      相关资源
      最近更新 更多