Error when using Custom Icon for Switch Component

Deadly 提交于 2021-01-29 17:57:48

问题


When I try to use the custom icon prop I get this error: index.js:1406 Warning: Failed prop type: Invalid prop icon supplied to ForwardRef(Switch), expected a ReactNode.

I have tried several things and I cannot make it work. Any ideas why it is not working?

<Switch
  checked={formik.values.roleBasedAccess}
  onChange={handleRoleBasedChange}
  icon={HexagonSwitch}
  value="roleBasedAccess"
/>

And the HexagonSwitch component:

import React from 'react';

const HexagonSwitch = () => {
        return (
            <svg width="24px" height="21px" viewBox="0 0 24 24">
                <g id="Add-on/Guided-Workflow/Pieces/Status-Indicator/Complete" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                    <polygon id="Polygon" fill="red" fill-rule="nonzero" points="12 3 20 7.5 20 16.5 12 21 4 16.5 4 7.5"></polygon>
                </g>
            </svg>
        );
};

回答1:


The "Failed prop type" message is telling you that it expects a node, but you are providing a component type.

Component Type: HexagonSwitch

Node (i.e. instance of the component type): <HexagonSwitch/>

Below is a working example.

import React from "react";
import Switch from "@material-ui/core/Switch";

const HexagonSwitch = () => {
  return (
    <svg width="24px" height="21px" viewBox="0 0 24 24">
      <g
        id="Add-on/Guided-Workflow/Pieces/Status-Indicator/Complete"
        stroke="none"
        strokeWidth="1"
        fill="none"
        fillRule="evenodd"
      >
        <polygon
          id="Polygon"
          fill="red"
          fillRule="nonzero"
          points="12 3 20 7.5 20 16.5 12 21 4 16.5 4 7.5"
        />
      </g>
    </svg>
  );
};
export default function Switches() {
  const [checked, setChecked] = React.useState(true);

  return (
    <div>
      <Switch
        checked={checked}
        onChange={event => setChecked(event.target.checked)}
        value="checkedA"
        icon={<HexagonSwitch />}
        checkedIcon={<HexagonSwitch />}
        inputProps={{ "aria-label": "secondary checkbox" }}
      />
    </div>
  );
}



来源:https://stackoverflow.com/questions/60323136/error-when-using-custom-icon-for-switch-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!