简体   繁体   中英

Template string literal inside of another template string literal

So the code I have currently, works, but I'm receiving the prefer-template: Unexpected string concatenation ESLINT error, which I'd like to avoid by perhaps knowing the correct way to do this with template strings literals.

Here's the code I have now:

<div className={`${styles.dataGridHeader} ${styles['columns' + this.props.data.headers.length]}`}>

I want to apply a class column1 , column2 , column3 , etc , depending on the number of columns in the data report, so that I can apply some specific styling to those elements.

What I have works, but is there a way to avoid using concatenation and only use template string literals?

For example:

<div className={`${styles.dataGridHeader} ${styles[`columns${this.props.data.headers.length}`]}`}>

Super ugly, and doesn't work, would love a more elegant solution.

How about this

const nColumn = 'columns' + this.props.data.headers.length
<div className={`${styles.dataGridHeader} ${styles[nColumn]}`}>

FYI there's an awesome library called classnames which applied to your code it looks something like this

import classNames from 'classnames'
const nColumn = 'columns' + this.props.data.headers.length
const divCls = classNames({
  [`${styles.dataGridHeader}`]: true,
  [`${styles[nColumn]}`]: true
})
<div className={divCls} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM