JSX + React中的动态tabIndex属性(Dynamic tabIndex attribute in JSX + React)

编程入门 行业动态 更新时间:2024-10-10 13:14:06
JSX + React中的动态tabIndex属性(Dynamic tabIndex attribute in JSX + React)

我将如何以同样的方式有条件地设置React组件上的tabIndex属性,比如设置'disabled'属性?

我需要能够设置值和/或一起删除属性。

首先尝试使整个属性键和值变量:

<div { tabIndex } ></div>

但编译器抱怨。

第二个想法是:

const div; if( condition ){ div = <div tabIndex="1"></div> }else{ div = <div></div> }

然而,这是不可取的,因为我的实际组件有大量的属性,我最终会有大量的重复代码。

我唯一的想法是使用ref,然后使用jQuery来设置tabindex属性,但我宁愿不必这样做。

有任何想法吗?

How would I set the tabIndex attribute on a React component conditionally in the same way, say the 'disabled' attribute is set?

I need to be able to set the value and/or remove the attribute all together.

First try was to make the entire attribute key and value a variable:

<div { tabIndex } ></div>

but the compiler complains.

Second thought was to:

const div; if( condition ){ div = <div tabIndex="1"></div> }else{ div = <div></div> }

However, this is not desirable since my actual components have tons of attributes on them and I'd end up having large amounts of duplicate code.

My only other thought was to use a ref, then use jQuery to set the tabindex attributes, but I would rather not have to do it that way.

Any Ideas?

最满意答案

你可以使用属性扩展运算符来完成它:

let props = condition ? {tabIndex: 1} : {}; let div = <div {...props} />

You can do it using the attribute spread operator:

let props = condition ? {tabIndex: 1} : {}; let div = <div {...props} />

更多推荐

本文发布于:2023-08-08 00:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   动态   JSX   React   attribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!