React非标准attribute异常告警:warning: React does not recognize the xxx prop on a DOM element

1、错误提示

​ Warning: React does not recognize the disableValue prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase disablevalue instead. If you accidentally passed it from a parent component, remove it from the DOM element。

img

2、原因分析

​ 这是React不能识别dom元素上的非标准attribute报出的警告,最终的渲染结果中React会移除这些非标准的attribute。

const MyCheckboxGroup: React.FC<MyCheckboxGroupProps> = props => {
  const { data, value, onChange, style, disableValue } = props;
 
  useEffect(()=>{
    onChange?.(value);
  }, [value])
 
  return (
    <Checkbox.Group
      {...props}
      value={value}
      onChange={ onChange}
      style={style || {}}
    >
      {Object.getOwnPropertyNames(data).map((item: any, index: any) => (
        <Checkbox value={Number.parseInt(item, 10).toString()} style={{ marginLeft: 0 }} disabled={disableValue?.includes(item)} key={index}>
          {
            typeof data[item] === 'string'
              ? data[item]
              : data[item]?.text
          }
        </Checkbox>
      ))}
    </Checkbox.Group>
  );
};

3、解决办法

​ 可以使用other接收属性参数,仅将other属性参数传递给子组件或对应的dom,自定义属性只组件自己使用。

const MyCheckboxGroup: React.FC<MyCheckboxGroupProps> = props => {
  const { data, value, onChange, style, disableValue, ...other } = props;
 
  useEffect(()=>{
    onChange?.(value);
  }, [value])
 
  return (
    <Checkbox.Group
      {...other}
      value={value}
      onChange={ onChange}
      style={style || {}}
    >
      {Object.getOwnPropertyNames(data).map((item: any, index: any) => (
        <Checkbox value={Number.parseInt(item, 10).toString()} style={{ marginLeft: 0 }} disabled={disableValue?.includes(item)} key={index}>
          {
            typeof data[item] === 'string'
              ? data[item]
              : data[item]?.text
          }
        </Checkbox>
      ))}
    </Checkbox.Group>
  );

扫描下方二维码,关注公众号:程序进阶之路,实时获取更多优质文章推送。


扫码关注

评论