Pra*_*een 8 reactjs react-native redux-form react-proptypes
我在redux-form字段中使用自定义组件,如下所示.
<Field name="height" parse={value => Number(value)} component={NumberInput} />
Run Code Online (Sandbox Code Playgroud)
自定义组件使用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;
Run Code Online (Sandbox Code Playgroud)
我想将为height字段输入的值存储为Number而不是String类型.因此,我正在使用parse将String转换为数字,如您在Field中所见.
我能够做到这一点,但继续得到黄箱警告:
Invalid prop 'value' of type 'number' supplied to 'TextInput', expected 'string'
Run Code Online (Sandbox Code Playgroud)
尝试将值PropType设置为any,string,number或oneOfType字符串或数字,似乎没有任何效果.还尝试在Field和TextInput中设置type ="number",以及type ="text".
任何帮助赞赏...
Kap*_*dav 39
基本上,在你的道具中你传递的是value的值.你必须以string的形式传递它.你可以像这样编辑你的代码:
<TextInput
keyboardType="numeric"
returnKeyType="go"
maxLength={3}
style={styles.inputStyle}
value={`${value}`} //here
onChangeText={onChange}
/>
Run Code Online (Sandbox Code Playgroud)
Spa*_*hut 13
这种方式应该更清洁:
<TextInput
value={yourValue ? String(yourValue) : null}
...
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14142 次 |
| 最近记录: |