我创建了如下组件:
import React from 'react';
import PropTypes from 'prop-types';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import { noop } from '../../utils';
const ButtonGroup = ({ options, value, onChange }) => {
console.log(onChange, 'onChange');
console.log(value, 'value');
return (
<ToggleButtonGroup
value={value}
exclusive
onChange={(event, val) => { onChange(val); }}
>
{
options.map(option => (
<ToggleButton value={option}>
{option}
</ToggleButton>
))
}
</ToggleButtonGroup>
);
};
ButtonGroup.propTypes = {
options: PropTypes.arrayOf(PropTypes.any),
onChange: PropTypes.func,
value: PropTypes.string,
};
ButtonGroup.defaultProps = {
options: [],
onChange: noop,
value: '',
};
export default ButtonGroup;
我正在尝试按以下方式使用它:
<Form onSubmit={handleSubmit(onCreateElement)}>
<label htmlFor="element-type">Select an option</label>
<div className="selectable">
<Field
name="element-type"
className="form-field"
component={ButtonGroup}
options={['One', 'Two', 'Three']}
/>
</div>
<button type="submit">Submit</button>
</Form>
但是redux-form从未将其onChange方法传递给我的组件。因此,我的组件不会更改所选值。
这是我的密码和框:https://codesandbox.io/s/yw7xj3vvx
答案 0 :(得分:0)
哦!天哪,这是一个很小的错误,我把它当作大错误。我需要在组件内部使用props.input.value
和props.input.onChange
。因此,我的新代码应如下所示:
import React from 'react';
import PropTypes from 'prop-types';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import { noop } from '../../utils';
const ButtonGroup = ({ options, input }) => {
return (
<ToggleButtonGroup
value={input.value}
exclusive
onChange={(event, val) => { input.onChange(val); }}
>
{
options.map(option => (
<ToggleButton value={option}>
{option}
</ToggleButton>
))
}
</ToggleButtonGroup>
);
};
ButtonGroup.propTypes = {
options: PropTypes.arrayOf(PropTypes.any),
input: PropTypes.objectOf(PropTypes.any),
};
ButtonGroup.defaultProps = {
options: [],
input: {},
};
export default ButtonGroup;
用法应保持不变。