最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change text colour depending on if condition react - Stack Overflow

programmeradmin2浏览0评论

I want to use something similar to getElementById in order to select my element and change the text colour. I currently have a unordered list, and wish to change the colour of each individual depending on an if condition.

<div style={styles.passwordRules}>
  <ul style={styles.listOne}>
    <li style={styles.li}><span style={styles.error} id="test">8 a 16 caratteri</span></li>
    <li style={styles.li}><span style={styles.fontNormal}>Carattere maiuscolo</span></li>
  </ul>
  <ul style={styles.listTwo}>
    <li style={styles.li}><span style={styles.fontNormal}>Un numero</span></li>
    <li style={styles.li}><span style={styles.fontNormal}>Carattere minuscolo</span></li>
  </ul>
  <ul style={styles.listThree}>
    <li style={styles.li}><span style={styles.fontLink}>Nessuna informazione personale</span></li>
  </ul>
</div>

Meaning that for instance, I would like something similar to this:

if(text === 'foo') {
//change colour to grey
}

Please note, I cannot use getElementById

I want to use something similar to getElementById in order to select my element and change the text colour. I currently have a unordered list, and wish to change the colour of each individual depending on an if condition.

<div style={styles.passwordRules}>
  <ul style={styles.listOne}>
    <li style={styles.li}><span style={styles.error} id="test">8 a 16 caratteri</span></li>
    <li style={styles.li}><span style={styles.fontNormal}>Carattere maiuscolo</span></li>
  </ul>
  <ul style={styles.listTwo}>
    <li style={styles.li}><span style={styles.fontNormal}>Un numero</span></li>
    <li style={styles.li}><span style={styles.fontNormal}>Carattere minuscolo</span></li>
  </ul>
  <ul style={styles.listThree}>
    <li style={styles.li}><span style={styles.fontLink}>Nessuna informazione personale</span></li>
  </ul>
</div>

Meaning that for instance, I would like something similar to this:

if(text === 'foo') {
//change colour to grey
}

Please note, I cannot use getElementById

Share Improve this question asked Nov 28, 2016 at 20:46 DaveDavidsonDaveDavidson 2061 gold badge8 silver badges25 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

Why not doing something like this:

<li className={text === 'foo' ? styles.class1 : styles.class2 } .../>

Branching out from Carl Edwards's answer then if it's only the color you want to change, this should do the trick:

<li style={{color: text === "foo" ? "trueColor" : "falseColor"}} ... />

You can do it for example using:

<li style={text ==== 'foo' ? _.extend(styles.style, styles.styleFoo) : styles.style }>

or if using ES6

<li style={text === 'fooo' ? Object.assign({}, styles.style, styles.styleFoo) : styles.style }>
发布评论

评论列表(0)

  1. 暂无评论