I tried using setState
in a TextInput
like so:
class AppS extends Component {
constructor(props){
super(props);
this.state = {
ShowText: '',
letter: ''
};
}
render(){
return(
<View>
<TextInput style ={{color: "green"}}
onChangeText = {(letter)=>this.setState({ letter })}>
</TextInput>
<Text style = {styleForApps.fon}> {this.state.letter} </Text>
<Text style = {styleForApps.body}> {this.state.ShowText} </Text>
</View>
);
}
}
When I experiment with setState
like this:
onChangeText = {(txt)=>this.setState({ letter: txt })}>
It works well. But when I changed it to:
onChangeText = {(txt)=>this.setState({ letter })}>
It always give a error "Can't find variable letter". I thought that setState
point the parameter in parenthesis that should be defined by txt
.
Can you explain please, I don't understand how exactly it passes the value to letter
.
I tried using setState
in a TextInput
like so:
class AppS extends Component {
constructor(props){
super(props);
this.state = {
ShowText: '',
letter: ''
};
}
render(){
return(
<View>
<TextInput style ={{color: "green"}}
onChangeText = {(letter)=>this.setState({ letter })}>
</TextInput>
<Text style = {styleForApps.fon}> {this.state.letter} </Text>
<Text style = {styleForApps.body}> {this.state.ShowText} </Text>
</View>
);
}
}
When I experiment with setState
like this:
onChangeText = {(txt)=>this.setState({ letter: txt })}>
It works well. But when I changed it to:
onChangeText = {(txt)=>this.setState({ letter })}>
It always give a error "Can't find variable letter". I thought that setState
point the parameter in parenthesis that should be defined by txt
.
Can you explain please, I don't understand how exactly it passes the value to letter
.
2 Answers
Reset to default 7You're attempting to use shorthand property definitions. This ES6 feature allows you to only specify the key if the key and value are the same. It does not take the value of the argument. That means when you do:
this.setState({
letter
});
It means this:
this.setState({
letter: letter
});
Because it desugars so that the key and value are the same. This then reports the error because letter
isn't defined. You could do:
(letter) => this.setState({ letter })
This works because you name the argument letter
, not txt
.
onChangeText
takes a function and passes the text that the user enters into that function, in your example you're naming that user input as txt
but inside of setState
you're not assigning this user input to letter
, what you're doing is specifying this.setState({letter})
which gets translated into this.setState({letter: letter})
and because you don't have a variable named letter you get an error
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744743655a4591179.html
评论列表(0条)