React Native TextInput组件状态绑定逻辑咨询:代码原理解析
Hey there! Let's break down exactly how this TextInput is updating your component's thing state, and why it doesn’t work the way you initially thought (like thing = TextInput.value).
First, let’s unpack the key line that’s confusing you:
onChangeText={(thing) => this.setState({thing})}
Here’s what’s happening step by step:
- The
onChangeTextProp: This is a built-in callback prop for React Native’s TextInput. Every time you type or delete something in the input, React Native automatically passes the full current text of the input as an argument to this callback. - The Arrow Function:
(thing) => ...is a concise function that takes the input text (we named itthinghere) and uses it to update the component’s state. - ES6 Object Shorthand:
this.setState({thing})is shorthand forthis.setState({thing: thing}). It tells React to update thethingproperty in your component’s state to match the text from the TextInput.
Why can’t you just do thing = TextInput.value?
React (and React Native) relies on a one-way data flow and requires explicit state updates with setState(). Here’s why direct assignment won’t work:
- If you directly modify state (like
this.state.thing = someValue), React won’t detect the change. That means the<Text>{this.state.thing}</Text>component won’t re-render to show the new value. setState()is React’s way of tracking state changes. When you call it, React knows to re-render the component (and any children that depend on that state), keeping your UI in sync with your data.
A more explicit (and maybe intuitive) version
If you want to make the connection clearer, you can rewrite the callback with a more descriptive parameter name, and add the value prop to explicitly bind the TextInput to state (this is called a "controlled component"):
<TextInput placeholder="default" value={this.state.thing} // Explicitly tie input value to state onChangeText={(inputText) => this.setState({thing: inputText})} />
This makes it obvious that:
- The input’s displayed value comes directly from
this.state.thing - Any change to the input triggers an update to
this.state.thing
Recap of your full code
Let’s reformat your original code for readability to see the whole picture:
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: ''}; // Initialize empty state } render(){ return ( <View style={{padding: 30}}> {/* Update state every time input text changes */} <TextInput placeholder="default" onChangeText={(thing) => this.setState({thing})}/> {/* Display the current state value */} <Text>{this.state.thing}</Text> </View> ); } }
Every time you type in the TextInput, onChangeText fires, updates this.state.thing, and React re-renders the Text component to show the new value.
内容的提问来源于stack exchange,提问作者Mathew

