道具类型失败:道具“值”无效

时间:2019-04-08 10:28:32

标签: react-native

每当我尝试输入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>
    );
};

能帮我找到问题吗?

3 个答案:

答案 0 :(得分: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}
                />

答案 1 :(得分:1)

onChange={(e) => onChangeText(e.text)}

onChangeText={onChangeText}

答案 2 :(得分:0)

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

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

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