我将如何以同样的方式有条件地设置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} />更多推荐
发布评论