动态设置 Prop Key JSX

Set Prop Key Dynamically JSX

我想知道是否可以在 JSX 中执行以下操作(此代码不起作用,只是我正在尝试执行的示例):

const propKey = 'someProp';
const jsx = <MyComponent [propKey]="some value" />;
// evaluates to <MyComponent someProp="some value">

我正在使用 babel es2015 stage-1,所以我可以像这样传播字典:

const extraProps = {[propKey]: 'some value'};
const jsx = <MyComponent {...extraProps} />

但是对于一个道具来说,这似乎太笨重了。我不想使用 React.createElement;我所有的 类 都是 es6 类。谢谢!

您可以使用 computed property names 在 JSX 中创建对象并传播它:

const propKey = 'someProp';
const jsx = <MyComponent { ...{ [propKey]: "some value" } } />;

JSX 是调用 React.createElement 的语法糖。所以一种解决方案是直接调用React.createElement

const element = React.createElement(MyComponent, {[propKey]: 'some value'});