Javascript JSX + React 中的动态 tabIndex 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36523225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic tabIndex attribute in JSX + React
提问by Jesse Lee
How would I set the tabIndex attribute on a React component conditionally in the same way, say the 'disabled' attribute is set?
我将如何以相同的方式有条件地在 React 组件上设置 tabIndex 属性,比如设置了“禁用”属性?
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?
有任何想法吗?
回答by Aaron Beall
You can do it using the attribute spread operator:
您可以使用属性传播运算符来做到这一点:
let props = condition ? {tabIndex: 1} : {};
let div = <div {...props} />
回答by debater
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. I'd need this to be confirmed by someone who knows for sure.
如果该属性的值为 null 或未定义,React 会从 JSX 元素中删除该属性。我需要得到肯定知道的人的确认。
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.
tabIndex
如果t1
为空,该属性将被删除。