希望我的问题很清楚,我主要是在寻找一种将属性动态附加到JSX输入的方法。
<input type="text" {variableAttribute}={anotherVariable} />
在不改写JSX从JS编译为常规HTML的方式的情况下,是否有可能做到这一点?
您可以使用计算的属性名称初始化对象,然后使用JSX Spread Attributes将其转换为attribute:
const DemoComponent = ({ variablePropName, variablePropValue }) => { const variableAttribute = { [variablePropName]: variablePropValue }; return ( <input type="text" { ...variableAttribute } /> ); };