小编典典

在JSX中拥有变量属性的最佳方法是什么?

reactjs

希望我的问题很清楚,我主要是在寻找一种将属性动态附加到JSX输入的方法。

<input type="text" {variableAttribute}={anotherVariable} />

在不改写JSX从JS编译为常规HTML的方式的情况下,是否有可能做到这一点?


阅读 486

收藏
2020-07-22

共1个答案

小编典典

您可以使用计算的属性名称初始化对象,然后使用JSX
Spread Attributes
将其转换为attribute:

const DemoComponent = ({ variablePropName, variablePropValue }) => { 
    const variableAttribute = { [variablePropName]: variablePropValue };
    return (
        <input type="text" { ...variableAttribute } />
    );
};
2020-07-22