【问题标题】:Redux-form, Invalid prop 'value' of type 'number' supplied to 'TextInput', expected 'string'Redux-form,提供给“TextInput”的“数字”类型的无效道具“值”,预期为“字符串”
【发布时间】:2017-10-27 23:04:11
【问题描述】:

我在 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;

我想将输入的高度字段值存储为数字而不是字符串类型。因此,我使用 parse 将字符串转换为数字,正如您在字段中看到的那样。

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

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

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

任何帮助表示赞赏...

【问题讨论】:

    标签: reactjs react-native redux-form react-proptypes


    【解决方案1】:

    基本上,在你的道具中,你传递的是数值的数值。你必须以字符串的形式传递它。你可以像这样编辑你的代码:

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

    【讨论】:

    • 我想使用 value={String(value)} 而不是 value={${value}} 会更高效,因为模板版本需要解析器来提取变量名和映射到字符串而不是直接转换为字符串。
    【解决方案2】:

    这种方式应该更干净:

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

    【讨论】:

      【解决方案3】:

      我会说这会更干净。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        相关资源
        最近更新 更多