Is there a JSX shortcut for assigning a value to a property when it has the same name?

时间:2017-08-04 12:42:25

标签: reactjs jsx

If I'm writing some JSX, is there a shortcut for some like this:

<MyComponent myProperty={myProperty} />

Such that I don't have to write myProperty twice?

I'm basically looking for a JSX equivalent to the literal object shorthand syntax in ES2015 and higher.

1 个答案:

答案 0 :(得分:2)

There is no such equivalent. The reason is that JSX mimics HTML syntax and for HTML both the following have a meaning:

// a property without value
<MyComponent myProperty />
// a property with a value
<MyComponent myProperty={myProperty} />

Therefore no shorthand syntax can be introduced.

You could use pure JS though:

 React.createElement("MyComponent", { myProperty });

or, you can pass all properties as a JS object:

<MyComponent {...{ myProperty }} />

I belive that both would decrease readability.