Dynamic tabIndex attribute in JSX + React

给你一囗甜甜゛ 提交于 2019-12-10 19:32:00

问题


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?


回答1:


You can do it using the attribute spread operator:

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



回答2:


I believe there is a simpler way (than Aaron's suggestion).

React removes an attribute from a JSX element if that attribute's value is null or undefined. 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.



来源:https://stackoverflow.com/questions/36523225/dynamic-tabindex-attribute-in-jsx-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!