React Native

React Native - 07 - 响应Text Input

2018-01-31  本文已影响20人  wanqijian

TextInput是一个允许用户输入文本的基本组件。它有一个onChangeText属性,它在每次文本改变时都会调用一个函数,而onSubmitEditing属性在提交文本时会调用一个函数。

例如,假设用户键入的内容是将他们的单词翻译为不同的语言。在这种新的语言中,每一个单词都以相同的方式写成:🍕。所以句子“你好,鲍勃”将被翻译为“🍕🍕🍕”。

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

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})}
            />
            <Text style={{padding: 10, fontSize: 42}}>
                {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
            </Text>
        </View>
        );
    }
}
image.png

在这个例子中,我们将文本存储在状态中,因为它随时间而改变。

上一篇 下一篇

猜你喜欢

热点阅读