在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 } />
);
};