我具有以下CustomInput组件:
import React from 'react';
const CustomInput = props => (
<div className="form-group">
<label className="form-label">{props.title}</label>
<input
className="form-input"
name={props.name}
type={props.inputType}
value={props.content}
onChange={props.controlFunc}
placeholder={props.placeholder}
/>
</div>
);
CustomInput.propTypes = {
inputType: React.PropTypes.oneOf(['text', 'number']).isRequired,
title: React.PropTypes.string.isRequired,
name: React.PropTypes.string.isRequired,
controlFunc: React.PropTypes.func.isRequired,
content: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
]).isRequired,
placeholder: React.PropTypes.string,
};
export default CustomInput;
这是我的表格:
import React, { PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form';
import CustomInput from '../components/CustomInput';
const renderMyStrangeInput = field => (
<CustomInput
inputType={'number'}
title={'How many items do you currently own?'}
name={'currentItems'}
controlFunc={param => field.input.onChange(param.val)}
content={{ val: field.input.value }}
placeholder={'Number of items'}
/>
);
class ItemsForm extends React.Component {
constructor(props) {
super(props);
}
render() {
const { handleSubmit } = this.props;
return (
<form className="container" onSubmit={handleSubmit}>
<h1>Nuevo Pedido</h1>
<Field name="myField" component={renderMyStrangeInput} />
<div className="form-group">
<button type="submit" className="btn btn-primary input-group-btn">Submit</button>
</div>
</form>
);
}
}
ItemsForm.propTypes = {
};
ItemsForm = reduxForm({
form: 'Items',
})(ItemsForm);
export default ItemsForm;
我可以渲染我的组件,但是内容类型存在一些问题。首先,如果将
CustomInput
设置为接受数字,则会得到:he specified value "[object Object]" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?
其次,如果将
inputType
设置为文本,它将呈现:[object Object]
因此,控制台发出以下警告:
Warning: Failed prop type: Invalid prop `content` supplied to `CustomInput`.
如何正确设置内容?
最佳答案
我认为问题是您正在尝试将字符串作为对象传递
<CustomInput
inputType="number"
title="How many items do you currently own?"
name="currentItems"
controlFunc={param => field.input.onChange(param.val)}
content={field.input.value}
placeholder="Number of items"
/>