在 React.cloneElement() 中设置 aria-label/aria-labelledby?

Setting aria-label/aria-labelledby within React.cloneElement()?

基本上,我正在尝试克隆一个元素并在 React.cloneElement 内更改其 aria-label。我有一个组件 - ButtonArrows - 它创建了两个 Button 组件,一个带有指向左侧的箭头图标,一个指向右侧。我希望能够以编程方式更改 aria-label,但连字符会引发错误。

这里有一些代码展示了我正在尝试做的事情:

const ButtonArrows = ({leftArrow, rightArrow, ...props})
  const prevButton = (
    <Button
      aria-label="Previous",
      icon={leftArrow}
    />
  );

  const nextButton = React.cloneElement(prevButton, {
    //this is where the problem is:
    aria-label="Next",
    icon={rightArrow}
  });

  return(<div {...props}>{prevButton}{nextButton}</div>);
}

显然我不能 aria-label="Next" 因为连字符。

有什么建议吗?不幸的是,当涉及到 aria 标签时,React 没有像 htmlFor(代表 html-for)这样的东西。我应该只在 Button 上放置一个 ariaLabel 道具并将其传递下去,还是有办法直接使用我缺少的 cloneElement 来完成它?

您应该可以在此处使用普通 JavaScript 对象:

const nextButton = React.cloneElement(prevButton, {
  'aria-label': 'Next',
  icon: rightArrow
});
const ButtonArrows = ({leftArrow, rightArrow, ...props})
  const prevButton = (
    <Button
      ariaLabel="Previous",
      icon={leftArrow}
    />
  );

  const nextButton = React.cloneElement(prevButton, {
    //this is where the problem is:
    ariaLabelledby="Next",
    icon={rightArrow}
  });

  return(<div {...props}>{prevButton}{nextButton}</div>);
}

将 aria-label 更改为 ariaLabel