Radio.Button封装,参考antd Radio
/components/Form/RadioButton.js
import React, { useState, memo } from 'react';
import PropTypes from 'prop-types';
import { Radio } from 'antd';
import classNames from 'classnames';
const { Group, Button } = Radio;
const {
arrayOf, oneOf, oneOfType, shape,
string, number, func,
} = PropTypes;
RadioButton.propTypes = {
dataSource: arrayOf(
shape({
label: string,
value: oneOfType([string, number]),
}),
).isRequired,
onChange: func.isRequired,
className: string,
buttonStyle: oneOf(['solid', 'outline']),
size: oneOf(['default', 'large', 'small']),
};
RadioButton.defaultProps = {
buttonStyle: 'solid',
size: 'default',
}
function RadioButton(props) {
const { dataSource, value: selected, onChange, className, size, buttonStyle } = props;
const [state, setState] = useState(() => {
return (selected !== undefined) ? selected : dataSource[0]?.value;
});
function radioChange({target}) {
setState(target.value);
onChange(target.value);
}
const attrs = {
size,
value: state,
buttonStyle,
className: classNames({[className]: Boolean(className)}),
onChange: radioChange,
}
return (
<Group {...attrs}>
{
dataSource.map(({ label, value }) =>
<Button value={value} key={value}>{label}</Button>)
}
</Group>
);
}
export default memo(RadioButton);
/components/Form/index.js
export { default as RadioButton } from './RadioButton';
dataSource数据格式
import { RadioButton } from '@components/Form';
const dataSource = [
{ value: 1, label: '股票' },
{ value: 2, label: '期货' },
{ value: 3, label: '黄金' },
{ value: 4, label: '债券' },
{ value: 5, label: '基金' },
];
<RadioButton
dataSource={dataSource}
onChange={radioChange}
size='small'
/>
PropTypes.arrayOf
PropTypes验证数组类型
// 数据格式
const items = [{label: '姓名', value: 'name'}, {label: '年龄', value: 'age'}];
// PropType校验数组类型
App..propTypes = {
dataSource: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
})
),
};
function App({dataSource}) {
// ...
}