简体   繁体   中英

react native understanding textInput component

Below I have some code that works fine (its based off this tutorial) however I don't understand why it works. Specifically I don't understand how the TextInput component knows that I want to set "thing" to the value of the TextInput. It would make more sense to me if there was something like thing = TextInput.value but as it is currently I don't understand it. If someone could explain to me the syntax here or direct me towards some resources on it that would be great. Please note, I have read this and the tutorial linked above but I still don't understand. Also in case this is not clear, the code below is stored in App.js and all it does is copy the current value of the TextInput to a Text component right below the TextInput.

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

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

    render(){
        return (
            <View style={{padding: 30}}>
                <TextInput placeholder="default" onChangeText={(thing) => this.setState({thing})}/>
                <Text>{this.state.thing}</Text>
            </View>
        );
    }
}

Specifically I don't understand how the TextInput component knows that I want to set "thing" to the value of the TextInput. So basically you have one onChange event attached so whenever you type onChange event gets triggered and set the value in the state.

<Text>{this.state.thing}</Text>

This line pick the value from state and shows it on your view.

If you want to send the value to TextInput , you can do it like this

<TextInput 
  placeholder="default"
  onChangeText={(thing) => this.setState({thing})}
  value= "your value"
/>

You are not setting any value to TextInput here. you are just typing and updating state. which is shown to you in

<Text>{this.state.thing}</Text>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM