Изменение состояния реагирования нативного ввода текста на фокус - PullRequest
0 голосов
/ 13 ноября 2018

Я пытаюсь заставить мой текст-заполнитель уйти в onFocus в компоненте React Native TextInput. Функция вызывается и состояние меняется, но заполнитель остается. Вот код компонента:

import React from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export class GeneralInput extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            placeholder: this.props.placeholder
        };
     }
    whenInputIsFocused() {
        console.log('Before changing the state');
        this.state.placeholder = "";
        console.log('After changing the state');
        console.log(this.state);
    }
  render() {
    console.log(this.state);
    return(
        <View style={styles.outerContainer}>
            <Text style={styles.labelText}>{this.props.labelText}</Text>
            <TextInput autoCapitalize='none' secureTextEntry={this.props.secureTextEntry} onFocus={this.whenInputIsFocused.bind(this)} underlineColorAndroid="transparent" keyboardType={this.props.type} returnKeyType={this.props.returnKeyType} placeholder={this.state.placeholder} placeholderTextColor='rgba(255, 255, 255, 0.3)' style={styles.inputStyles} />
        </View>
    );
  }
}

Вот вывод журнала консоли:

[09:39:18] Before changing the state
[09:39:18] After changing the state
[09:39:18] Object {
[09:39:18]   "placeholder": "",
[09:39:18] }

Почему мой заполнитель TextInput не исчезает, даже если функция вызывается и состояние обновляется?

1 Ответ

0 голосов
/ 13 ноября 2018

Это нормальное поведение.Заполнитель исчезнет, ​​если вы введете текст, но вам не хватает двух важных свойств.

<TextInput>
  onChangeText={(text) => this.setState({text})}
  value={this.state.text}
</TextInput>

value устанавливает текст (не заполнитель) и сохраняет его внутри TextInput.onChangeText изменяет текст, устанавливая состояние.При запуске this.state.text должен содержать пустую строку ""

edit: если вы хотите, чтобы заполнитель исчез, вам нужно установить его как

this.setState({placeholder: ""});

Использованиеthis.setState() вызовет повторную попытку.

...