简体   繁体   English

JSX + React 中的动态 tabIndex 属性

[英]Dynamic tabIndex attribute in JSX + React

How would I set the tabIndex attribute on a React component conditionally in the same way, say the disabled attribute is set?我将如何以相同的方式有条件地在 React 组件上设置tabIndex属性,比如设置了disabled属性?

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.我唯一的其他想法是使用 ref,然后使用 jQuery 来设置tabindex属性,但我宁愿不必那样做。

Any Ideas?有任何想法吗?

You can do it using the attribute spread operator :您可以使用属性传播运算符来做到这一点:

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

I believe there is a simpler way (than Aaron's suggestion).我相信有一种更简单的方法(比 Aaron 的建议)。

React removes an attribute from a JSX element if that attribute's value is null or undefined.如果该属性的值为 null 或未定义,React 会从 JSX 元素中删除该属性。 I'd need this to be confirmed by someone who knows for sure.我需要得到肯定知道的人的确认。

Therefore you can use something like this:因此你可以使用这样的东西:

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

The tabIndex attribute will be removed if t1 is null.如果t1为空,则tabIndex属性将被删除。

For example, we have three attributes, tabIndex, class and id.例如,我们有三个属性,tabIndex、class 和 id。

let tabIndex;
let id;
let className = "tab";
let props = {
    tabIndex,
    className,
    id,
}
let div = <div {...props} />

undefined/null value props will not add in div, so the render result is undefined/null 值 props 不会添加到 div 中,所以渲染结果是

<div class="tab" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM