在JSX中拥有变量属性的最佳方法是什么? [英] What is the best way to have variable attributes in JSX?
本文介绍了在JSX中拥有变量属性的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
希望我的问题很清楚,我主要是在寻找一种将属性动态附加到JSX输入的方法.
Hopefully my question is clear, I'm mainly looking for a way to dynamically attach attributes to a JSX input.
<input type="text" {variableAttribute}={anotherVariable} />
在不重写JSX从JS编译为常规HTML的方式的情况下,是否有可能做到这一点?
Is something like this possible without overriding the way JSX compiles from JS to regular HTML?
推荐答案
您可以使用 JSX传播属性以将其转换为属性:
You can initialize an object with a computed property name, and then use JSX Spread Attributes to convert it to attribute:
const DemoComponent = ({ variablePropName, variablePropValue }) => {
const variableAttribute = { [variablePropName]: variablePropValue };
return (
<input type="text" { ...variableAttribute } />
);
};
这篇关于在JSX中拥有变量属性的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文