首页 > 解决方案 > 单击按钮后显示输入字段 react-native

问题描述

我正在学习 react-native,我想做一些简单的事情,用户可以输入一些信息,如姓名或其他信息,然后当他/她点击按钮时,它会在屏幕上显示你好,某某。我将onChangeText设置设置state为用户传递的内容,但它没有更新。同样单击该按钮不显示任何内容。我将在下面粘贴我的代码。任何帮助或建议。

app.js

import { Button } from "react-native";
import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Alert,
  TextInput
} from "react-native";

const instructions = Platform.select({
  ios: "Press Cmd+R to reload,\n" + "Cmd+D or shake for dev menu",
  android:
    "Double tap R on your keyboard to reload,\n" +
    "Shake or press menu button for dev menu"
});

type Props = {};
export default class App extends Component<Props> {
  constructor() {
    super();
    this.state = {
      text: "Hello "
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = typedText => {
    this.setState({
      text: typedText
    });
    console.log(text);
  };
  render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.value}</Text>
        <Button onPress={this.handleChange} title="Click Me " />
        <TextInput
          placeholder="Type your name here"
          onChangeText={typedText => {
            this.setState({
              text: typedText
            });
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

标签: reactjsreact-native

解决方案


您也在 handlechange (onpress 函数)中设置状态,这根本不需要。您的 onPress 中不会有文本参数,您正在重置状态中的文本值。并且 handleChange 中的文本将是未定义的,因为您没有在任何地方设置它。

代码应该如下所示。

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      text: "Hello "
    };
    this.handleChange = this.handleChange.bind(this);
  }
  onPress = () => {
    console.log("current ==> ", this.state);
    alert(this.state.text);
  };
  handleChange = typedText => {
    console.log("update => ", typedText);
    this.setState(
      {
        text: typedText
      }
    );
  };
  render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.value}</Text>
        <Button onPress={this.onPress} title="Click Me " />
        <TextInput
          placeholder="Type your name here"
          onChangeText={this.handleChange}
        />
      </View>
    );
  }
}

推荐阅读