首页 > 解决方案 > 带有本机反应的文本输入

问题描述

我正在尝试使用本机反应创建一个文本输入框。

模板(有效)类似于:

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 SyntaxError: [Path]\App.js: Unexpected token, expected ";"

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

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

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

标签: androidreact-native

解决方案


在 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

推荐阅读