Radio.Button封装,参考antd Radio
image.png
/components/Form/RadioButton.js

  1. import React, { useState, memo } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { Radio } from 'antd';
  4. import classNames from 'classnames';
  5. const { Group, Button } = Radio;
  6. const {
  7. arrayOf, oneOf, oneOfType, shape,
  8. string, number, func,
  9. } = PropTypes;
  10. RadioButton.propTypes = {
  11. dataSource: arrayOf(
  12. shape({
  13. label: string,
  14. value: oneOfType([string, number]),
  15. }),
  16. ).isRequired,
  17. onChange: func.isRequired,
  18. className: string,
  19. buttonStyle: oneOf(['solid', 'outline']),
  20. size: oneOf(['default', 'large', 'small']),
  21. };
  22. RadioButton.defaultProps = {
  23. buttonStyle: 'solid',
  24. size: 'default',
  25. }
  26. function RadioButton(props) {
  27. const { dataSource, value: selected, onChange, className, size, buttonStyle } = props;
  28. const [state, setState] = useState(() => {
  29. return (selected !== undefined) ? selected : dataSource[0]?.value;
  30. });
  31. function radioChange({target}) {
  32. setState(target.value);
  33. onChange(target.value);
  34. }
  35. const attrs = {
  36. size,
  37. value: state,
  38. buttonStyle,
  39. className: classNames({[className]: Boolean(className)}),
  40. onChange: radioChange,
  41. }
  42. return (
  43. <Group {...attrs}>
  44. {
  45. dataSource.map(({ label, value }) =>
  46. <Button value={value} key={value}>{label}</Button>)
  47. }
  48. </Group>
  49. );
  50. }
  51. export default memo(RadioButton);

/components/Form/index.js

  1. export { default as RadioButton } from './RadioButton';

dataSource数据格式

  1. import { RadioButton } from '@components/Form';
  2. const dataSource = [
  3. { value: 1, label: '股票' },
  4. { value: 2, label: '期货' },
  5. { value: 3, label: '黄金' },
  6. { value: 4, label: '债券' },
  7. { value: 5, label: '基金' },
  8. ];
  9. <RadioButton
  10. dataSource={dataSource}
  11. onChange={radioChange}
  12. size='small'
  13. />

PropTypes.arrayOf

PropTypes验证数组类型

  1. // 数据格式
  2. const items = [{label: '姓名', value: 'name'}, {label: '年龄', value: 'age'}];
  3. // PropType校验数组类型
  4. App..propTypes = {
  5. dataSource: PropTypes.arrayOf(
  6. PropTypes.shape({
  7. label: PropTypes.string,
  8. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
  9. })
  10. ),
  11. };
  12. function App({dataSource}) {
  13. // ...
  14. }