文本输入与本机反应

时间:2019-11-23 07:07:20

标签: android react-native

我正在尝试创建一个带有本机反应的文本输入框。

模板(有效)类似于:

const App: () => React$Node = () => {

  return (
    <>
      <Text>Hello world</Text>
    </>
  );
};

export default App;

我尝试了以下文本输入方案:

const App: () => React$Node = () => {

  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  return (
    <>
      <Text>Hello world</Text>
      <TextInput
        style={{height: 40}}
        placeholder="Type here to translate!"
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {this.state.text.split(' ').map((word) => word && '?').join(' ')}
      </Text>
    </>
  );
};

我收到以下错误:

  

错误:TransformError语法错误:[Path] \ App.js:意外令牌,预期为“;”

通常,格式(也可以)是这样的:

export default class PizzaTranslator extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
          value={this.state.text}
        />
        <Text style={{padding: 10, fontSize: 42}}>
          {this.state.text.split(' ').map((word) => word && '?').join(' ')}
        </Text>
      </View>
    );
  }
}

但是我认为,应该有一种方法可以使用箭头功能将文本输入添加到模板中。 有什么明显的我想念的吗?

2 个答案:

答案 0 :(得分:0)

在React native中创建文本输入非常简单。这应该有帮助。

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

const App: () => React$Node = () => {

const [value, setValue] = useState()
  return (
    <>
      <Text>Hello world</Text>
      <TextInput
        style={{height: 40}}
        placeholder="Type here to translate!"
        onChangeText={(text) => setValue(text)}
        value={value}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {value
        .split(" ")
        .map(word => word && "?")
        .join(" ")}
      </Text>
    </>
  );
};

export default App

答案 1 :(得分:0)

您能否尝试此代码段,只需复制粘贴即可?它对我有效。我猜您的代码格式会创建 SyntaxError

import React, { useState } from "react";
import { SafeAreaView, View, Text, TextInput } from "react-native";

const App = () => {
  const [text, setText] = useState("");
  return (
    <SafeAreaView>
      <View style={{ padding: 10 }}>
        <TextInput
          style={{ height: 40 }}
          placeholder="Type here to translate!"
          onChangeText={text => setText(text)}
          value={text}
        />
        <Text style={{ padding: 10, fontSize: 42 }}>
          {text
            .split(" ")
            .map(word => word && "?")
            .join(" ")}
        </Text>
      </View>
    </SafeAreaView>
  );
};

export default App;