0

我试图让我的占位符文本在 React Native TextInput 组件中消失 onFocus。正在调用该函数并且状态正在更改,但占位符仍然存在。这是组件代码:

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 占位符没有消失,即使正在调用该函数并且状态已更新?

4

1 回答 1

2

这是正常行为。如果您输入文本,占位符将消失,但您缺少两个重要属性。

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

value设置文本(不是占位符)并将其保存在 TextInput 中。 onChangeText通过设置状态更改文本。开始this.state.text时应包含空字符串""

编辑:如果你想让占位符消失,你需要设置它

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

使用this.setState()将强制重新渲染。

于 2018-11-13T16:57:16.900 回答