【问题标题】:Failed prop type: Invalid prop 'value'失败的道具类型:无效的道具“价值”
【发布时间】:2019-04-08 10:28:31
【问题描述】:

每当我尝试输入 TextInput 时,我都会收到以下警告: 提供给“textinput”预期“字符串”的“对象”类型的“道具”类型无效的道具“值”失败

LoginForm.js

import React, { Component } from 'react';
import { Card, CardSection, Button, Input } from './common';

class LoginForm extends Component {

    state = { email: '', password: '', error: '' };

    render() {
        return (
            <Card>
                <CardSection>
                    <Input 
                    label='Email'
                    placeholder='user@gmail.com'
                    value={this.state.email}
                    onChangeText={(email) => this.setState({ email: email } )}
                    />
                </CardSection>

Input.js

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

const Input = ({ label, value, onChangeText, placeholder, secureTextEntry }) => {
    return (
        <View style={styles.containerStyle}>
            <Text style={styles.labelStyle}>{ label }</Text>
                <TextInput
                secureTextEntry={secureTextEntry}
                placeholder={placeholder}
                style={styles.inputStyle}
                value={value}
                onChange={onChangeText}
                autoCorrect={false}
                />
        </View>
    );
};

你能帮我找出问题吗?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    你需要绑定的事件监听器是onChangeText

    onChangeText 需要一个字符串参数...其中onChange 需要一个这种形式的对象:nativeEvent: { eventCount, target, text} ...这就是您收到此错误的原因...

    <Text style={styles.labelStyle}>{ label }</Text>
                    <TextInput
                    secureTextEntry={secureTextEntry}
                    placeholder={placeholder}
                    style={styles.inputStyle}
                    value={value}
                    onChangeText={onChangeText} // <--Look at this
                    autoCorrect={false}
                    />
    

    【讨论】:

    • 哦,太尴尬了!!非常感谢!!
    • 它们非常相似......而且有点令人困惑:)
    • 是的,我知道...感谢您的帮助:)
    【解决方案2】:
    onChange={(e) => onChangeText(e.text)}
    

    onChangeText={onChangeText}
    

    【讨论】:

    • 非常感谢!这是一个错字,我没有注意到它
    【解决方案3】:

    当您尝试输入类型为number 而不是string 的值时,会出现您提到的错误或Warning: Failed prop type: Invalid prop value of type number supplied to TextInput, expected string

    为了避免错误并遵循 react-native 的最佳实践,使用 String() 函数包装输入值,如下所示:

    <TextInput
      value={String(this.props.value)}
      onChange = {this.props.onChange}
      placeholder={"جستجو"}
      blurOnSubmit={false}
      style={{flex:0.9}}
      returnKeyType="done"
    />
    

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2021-07-27
      • 2017-07-31
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2019-02-07
      • 2019-05-17
      • 2017-12-23
      相关资源
      最近更新 更多