2016-09-15 4 views
0

У меня есть TextInput с maxLength 100 в моей сцене, и я хочу добавить счетчик, ниже которого отображается что-то вроде «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> 

ответ

1

Функция onChangeText возвращает текстовый объект, который может быть измерен. Таким образом, сделать что-то вроде:

const textLength = text.length; 
const sub = 100 - textLength; 
this.setState({textLength: sub}); 
+0

вы имеете в виду: onChangeText = { const textLength = text.length; const sub = 100 - textLength; this.setState ({textLength: sub}); this.setState ({текст: текст}); } –

+1

Да, но не забудьте подать аргумент, т. Е. (Текст) => {...} – nmac

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> 
    ); 
    } 
} 
Смежные вопросы