Redux 形式,提供给 'TextInput' 的 'number' 类型的无效道具 'value',应为 'string'

Redux-form, Invalid prop 'value' of type 'number' supplied to 'TextInput', expected 'string'

我在 redux-form 字段中使用自定义组件,如下所示。

<Field name="height" parse={value => Number(value)} component={NumberInput} />

自定义组件使用 React Native 的 TextInput 组件,它看起来像这样:

import React from 'react';
import PropTypes from 'prop-types';
import { View, Text, TextInput, StyleSheet } from 'react-native';
import { COLOR_PRIMARY } from '../constants';

const styles = StyleSheet.create({
  inputStyle: {
    height: 30,
    width: 50,
    marginBottom: 10,
    borderColor: COLOR_PRIMARY,
    borderWidth: 2,
    textAlign: 'center',
  },
  errorStyle: {
    color: COLOR_PRIMARY,
  },
});

const NumberInput = (props) => {
  const { input: { value, onChange }, meta: { touched, error } } = props;
  return (
    <View>
      <TextInput
        keyboardType="numeric"
        returnKeyType="go"
        maxLength={3}
        style={styles.inputStyle}
        value={value}
        onChangeText={onChange}
      />
      {touched &&
        (error && (
          <View>
            <Text style={styles.errorStyle}>{error}</Text>
          </View>
        ))}
    </View>
  );
};

NumberInput.propTypes = {
  meta: PropTypes.shape({
    touched: PropTypes.bool.isRequired,
    error: PropTypes.string,
  }).isRequired,
  input: PropTypes.shape({
    // value: PropTypes.any.isRequired,
    onChange: PropTypes.func.isRequired,
  }).isRequired,
};

export default NumberInput;

我想将为高度字段输入的值存储为数字而不是字符串类型。因此,我正在使用解析将字符串转换为数字,如您在字段中所见。

我能够做到这一点,但不断收到黄框警告:

 Invalid prop 'value' of type 'number' supplied to 'TextInput', expected 'string'

已尝试将值 PropType 设置为任意、字符串、数字或 oneOfType 字符串或数字,似乎没有任何效果。还尝试在 Field 和 TextInput 中设置 type="number",以及 type="text".

感谢任何帮助...

基本上,在您的道具中,您传递的数值 value.You 必须以 string.You 的形式传递,可以这样编辑您的代码:

<TextInput
  keyboardType="numeric"
  returnKeyType="go"
  maxLength={3}
  style={styles.inputStyle}
  value={`${value}`} //here
  onChangeText={onChange}
/>

这种方式应该更干净:

<TextInput
  value={yourValue ? String(yourValue) : null}
  ...
/>

我会说这样会更干净。

<TextInput
  value={yourValue && String(yourValue)}
  ...
/>