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



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

下面是一些代码,显示了我正在尝试执行的操作:

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"

有什么建议吗?不幸的是,React 没有像htmlFor这样的东西(代表html-for(,当它出现在咏叹调标签上时。我应该在按钮上放一个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

最新更新