简体   繁体   中英

How does setState work in this example?

I'm reading over the React Native tutorial and I'm fairly confused about the TextInput section:

<TextInput
    style={{height: 40}} 
    placeholder="Type here to translate!"
    onChangeText={(text) => this.setState({text})}
/>

What I understand:

I realize that onChangeText={(txt) => this.setState({text: txt})} works and that makes sense to me, since the parameter is being applied to the state text


What I don't understand:

I don't understand how onChangeText={(text) => this.setState({text})} works. Why does the parameter text have to be named the same as the state text ? I understand that it is equivalent to onChangeText={(text) => this.setState({text: text})} , but I don't understand why. If the parameter was just being passed to the state variable, then onChangeText={(txt) => this.setState({text})} would work, but it doesn't.

I tried searching for an answer and asking multiple people, but I haven't received a clear explanation yet.

You're seeing shorthand object properties , a feature new in ES2015. If the property and value are the same, then you don't need to provide the value:

const obj = {
  foo
};

Is the same as:

const obj = {
  foo: foo
};

So in this case, it is equivalent to (and desugars to):

(text) => this.setState({ text: text })

The reason why it doesn't work when you try:

(txt) => this.setState({ text })

Is because in the first example, text , the value of the property refers to the argument of the arrow function:

(text) => this.setState({ text: text })
//                              ^^^^ refers to the argument `text`

In the second snippet, text is the value, but there is no text variable because you changed the argument to txt , thus it does not work:

(txt) => this.setState({ text: text })
//                              ^^^^ refers to the argument `text` but it doesn't exist, it is called `txt`!

The value must be the same as the key.

this.setstate() is a function. When you instantiate the state object in your Constructor this.state = {foo: bar} you are creating an object. So when you call this.setState() you are updating that object. So your example you could write it like this and have the same result:

onChangeText={(txt) => this.setState({text: txt})}

To access this, you would use this.state.text

此功能是ES2015(ES6)的属性简写

If I understand your question, what you have a hard time understanding is a new feature in es6 called object literal property value shorthand . https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

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