尝试输入文本输入时出现综合事件错误

Synthetic event error when trying to type in textinput

我正在用 react-native 构建一个登录页面。每当我在用户名字段中键入内容时,我都会收到警告:出于性能原因,合成事件被重用 并且文本标记的值未按需要更改。我写的代码如下:

export default class LoginScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        }
    }

    login = async () => {
        // const result = await appLogin(this.state.userName, this.state.password);
        console.log(`${this.state.username} ${this.state.password}`);
    };

    render() {
        return <View style={loginStyles.container}>
            <ImageBackground
                source={require('../../../assets/images/login.jpg')}
                style={loginStyles.backgroundImage}>
                <View style={loginStyles.titleContainer}>
                    <Text style={{fontSize: 40, color: 'grey', paddingVertical: 40}}>{this.state.username}</Text>
                </View>
                <View style={loginStyles.nestedContainer}>
                    <TextInput
                        placeholder={'username / email'}
                        style={[style.inputStyle, style.colorBlue]}
                        onChange={(username) => this.setState(username)}
                    />
                    <TextInput
                        placeholder={'password'}
                        textContentType="password"
                        secureTextEntry={true}
                        autoCapitalize="none"
                        autoCorrect={false}
                        style={[style.inputStyle, style.colorBlue]}
                        onChange={(password) => this.setState(password)}
                    />
                    <CustomRoundedButton
                        text={'Login'}
                        buttonStyle={[style.bgPrimary]}
                        onPress={this.login}
                        textStyle={[style.text20, {color: 'white'}]}
                    />
                </View>
            </ImageBackground>
        </View>
    }
};

这是此警告的屏幕截图。 请帮我找到解决这个问题的方法。

替换

 onChange={(username) => this.setState(username)}

onChangeText={(username) => this.setState({ username })}

onChange={(password) => this.setState(password)}

onChangeText={(password) => this.setState({ password })}

希望对您有所帮助!

TextInput 的 onChange 处理程序被传递给一个本机事件对象,您在匿名函数中将其命名为 username。 React 状态更新是异步的,所以当 React 更新状态时,事件早已消失(被放回事件池中)。

改用onChangeText,它接收更新的输入文本值。

onChangeText={(username) => this.setState(username)}

更新所有输入更改回调以使用 onChangeText

您的代码:

onChange={(username) => this.setState(username)}

你应该为此改变:

onChangeText={(username) => this.setState({ username })}