我正在开发 ReactNative 移动应用程序。 WebApp 运行顺利,一切正常。但是,当我将所有内容传输到移动部分时,当我在输入字段中输入文本时,我遇到了错误。我做错了什么以及我的错误是什么?这是我的代码:
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App extends React.Component {
state={
message:"Hi {name}, your rating for this app is {rating}"
}
handleName=()=>{
this.setState({
message:"Hi "+this.refs.name.value+", your rating for this app is {rating}"
})
}
handleRating=()=>{
this.setState({
message:"Hi "+this.refs.name.value+", your rating for this app is "+this.refs.rating.value
})
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Your Name"
ref="name"
onChangeText={this.handleName}
/>
<TextInput
placeholder="Your Rating"
ref="rating"
onChangeText={this.handleRating}
/>
<View>{this.state.message}</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
我不认为像这样引用
TextInput
组件(使用字符串引用)是实现此目的的最佳方法。但是,如果您愿意,可以使用 this.refs.name._lastNativeText
来访问 TextInput 的当前值,而不是 this.refs.name.value
。
在我看来,更好的方法是使用
onChangeText()
回调返回的值。你可以这样做:
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: null,
rating: null,
message: null,
}
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Your Name"
onChangeText={text => this.setState({name: text})}
/>
<TextInput
placeholder="Your Rating"
onChangeText={text => this.setState({rating: text})}
/>
{ this.state.name && this.state.rating &&
<Text>Hi {this.state.name}, your rating for this app is {this.state.rating}.</Text>
}
</View>
);
}
}
我还没有测试过这段代码,如果您遇到一些错误,请在下面评论。
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App extends React.Component {
state={
message:"Hi {name}, your rating for this app is {rating}"
}
handleName=()=>{
this.setState({
message:"Hi "+this.refs.name.value+", your rating for this app is {rating}"
})
}
handleRating=()=>{
this.setState({
message:"Hi "+this.refs.name.value+", your rating for this app is "+this.refs.rating.value
})
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Your Name"
ref="name"
onChangeText={this.handleName}
/>
<TextInput
placeholder="Your Rating"
ref="rating"
onChangeText={this.handleRating}
/>
<View>{this.state.message}</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});