【问题标题】:Setting aria-label/aria-labelledby within React.cloneElement()?在 React.cloneElement() 中设置 aria-label/aria-labelledby?
【发布时间】:2017-07-26 14:41:58
【问题描述】:

基本上,我正在尝试克隆一个元素并在 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 reactjs accessibility wai-aria


    【解决方案1】:

    您应该可以在这里使用纯 JavaScript 对象:

    const nextButton = React.cloneElement(prevButton, {
      'aria-label': 'Next',
      icon: rightArrow
    });
    

    【讨论】:

    • 完美!我一直在思考 React 如何使用 htmlFor 和 className,我完全想多了。
    • @kbuechner 很高兴我能帮上忙!如果我的回答解决了您的问题,请单击大复选框接受它作为答案。
    【解决方案2】:
    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

    【讨论】:

    • 如果这与其他带有连字符的属性一样,“L”不应该大写吗,就像在 ariaLabel 和 ariaLabelledby 中一样?
    猜你喜欢
    • 2013-11-06
    • 2020-10-31
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多