我有以下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`.
如何正确设置内容?
答案 0 :(得分:5)
我认为问题在于您正在尝试将字符串作为对象
<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"
/>
答案 1 :(得分:1)
您通过道具传递对象,您必须传递字符串或数字。
content={{ val: field.input.value }} // no!
content={field.input.value} // yes! :)