首页 > 解决方案 > 如何在本机反应中获取文本输入的文本?

问题描述

如何用 React 语法编写这个语句,就像在 ios 中一样:

txt1.text = label.text 

我尝试了很多但失败了。

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

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

onPress = () => {
this.setState({
  //textValue.Text: TextInputValue,
  //newText: textValue
});
  };

render() {
return (
  <View style={{ paddingTop: 25 }}>

    <TextInput
      style={{ height: 40 }}
      placeholder="Type here to! Translate"
      onChangeText={TextInputValue => this.setState({ TextInputValue })}
    />
    <Button title="Change Text" onPress={this.onPress} 
    />

    <Text>
      {this.state.newText}
    </Text>
  </View>
);
}
 }

按下按钮时,我想获取文本textinput并将其显示在文本(标签)上

标签: reactjsreact-native

解决方案


两个缺失的元素:

  1. newText在状态结构中定义。
state = {
  TextInputValue: '', // for onChangeText handler
  newText: '', // for button onClick handler
};
  1. 实现按钮onClick处理程序以设置newText状态。
onPress = () => {
  this.setState({
    newText: this.state.TextInputValue,
  });
}

请参阅代码沙盒演示


推荐阅读