改变焦点上反应本机文本输入的状态

Changing state of react native textinput on focus

我试图让我的占位符文本在 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 占位符没有消失,即使正在调用函数并更新状态?

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

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

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

编辑:如果想让占位符消失,需要通过

设置

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

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