我的场景中有一个带有maxLength 100的TextInput,我想在下面添加一个计数器,显示类似" 38/100",用' onChangeText'进行自动更新。
所以我必须弄清楚输入值的长度,以某种方式将它存储在this.state.textLength中,同时将值本身存储到this.state.text中,但我不知道如何在" onChangeText = {(text)=> ...}"功能
这是我的简化代码:
export class RequestScene extends Component {
constructor() {
super();
this.state={
text: '',
textLength: 0,
category: '',
time: ''
};
}
render(){
return(
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}}>
<View style={{
height: 200
}}>
<TextInput style={{
height: 200,
width: 360,
borderColor: 'lightgray',
borderWidth: 1,
padding: 3,
borderRadius: 3,
fontSize: 24}}
maxLength={100}
placeholder='무슨 상황인지 간단하게 써주세요'
multiline={true}
// this is where I am stuck. What should I do with 'textLength'?
onChangeText={
(text)=>this.setState({text})
(text)=>this.setState({textLength})
}
/>
<Text style={{
fontSize:10,
color:'lightgrey',
textAlign: 'right'
}}>
// currently this counter only shows '0/100'
{this.state.textLength}/100
</Text>
答案 0 :(得分:2)
onChangeText()
函数返回一个字符串。你可以这样做:
const maxLength = 100;
this.setState({
textLength: maxLength - text.length,
text, // same as `text: text`
});
答案 1 :(得分:0)
为了使代码更易于阅读,您可以在onChangeText处理程序中调用一个单独的方法,该方法以下列方式更新textLength
:
export class RequestScene extends Component {
constructor() {
super();
this.maxLength = 100;
this.state={
textLength: 0,
};
}
onChangeText(text){
this.setState({
textLength: this.maxLength - text.length
});
}
render(){
return (
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}}>
<View style={{
height: 200
}}>
<TextInput style={{
height: 200,
width: 360,
borderColor: 'lightgray',
borderWidth: 1,
padding: 3,
borderRadius: 3,
fontSize: 24}}
maxLength={100}
placeholder='무슨 상황인지 간단하게 써주세요'
multiline={true}
onChangeText={this.onChangeText.bind(this)}
/>
<Text style={{
fontSize:10,
color:'lightgrey',
textAlign: 'right'
}}>
// currently this counter only shows '0/100'
{this.state.textLength}/100
</Text>
</View>
</View>
);
}
}
答案 2 :(得分:0)
要获取输入字段的长度,请尝试
handleEmailOtp = emailOtpString => {
this.setState({emailOtp: emailOtpString});
const otpLength = emailOtpString.length.toString(); //here
otpLength == 6
? this.setState({otpTyped: true})
: this.setState({otpTyped: false});
};
答案 3 :(得分:0)
import React, { Component } from 'react'
import { View, Text, TextInput } from 'react-native'
export default class App extends Component {
state = {
text: ''
}
render() {
return (
<View style={{ padding: 10 }}>
<TextInput style={{ borderWidth: 1 }} numberOfLines={3} maxLength={100} multiline={true} onChangeText={(text) => this.setState({ text: text })} />
<Text>{100 - this.state.text.length}/100 Characters</Text>
</View>
)
}
}