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

javascript - How to add class if id is true in React? - Stack Overflow

programmeradmin2浏览0评论

I have a list as follows:

<div id="123" className="panel"></div>
<div id="456" className="panel"></div>
<div id="789" className="panel"></div>
<div id="101" className="panel"></div>

So if id equals true add class open, if false remove open.

Is this possible in react, I've tried using ref but that hasn't worked.

I have a list as follows:

<div id="123" className="panel"></div>
<div id="456" className="panel"></div>
<div id="789" className="panel"></div>
<div id="101" className="panel"></div>

So if id equals true add class open, if false remove open.

Is this possible in react, I've tried using ref but that hasn't worked.

Share asked May 25, 2017 at 10:17 user1177860user1177860 5094 gold badges13 silver badges24 bronze badges 4
  • " if id equals true" when and How id will be true? – Rohit Choudhary Commented May 25, 2017 at 10:19
  • How are you rendering this list? It sounds like you should be using a prop, not manipulating the DOM to add a class after rendering. – Tom Fenech Commented May 25, 2017 at 10:21
  • I have some points and each one has an id, onClick the id gets returned – user1177860 Commented May 25, 2017 at 10:21
  • Post some code. Your problem statement is not clear! – Rohit Choudhary Commented May 25, 2017 at 10:23
Add a ment  | 

1 Answer 1

Reset to default 5

React handles making the necessary changes to the DOM based on what you render, so instead of thinking in terms of adding and removing classNames when state changes, think in terms of how your render method's output changes.

e.g. if you have some selectedId state which represents the currently-selected id:

render() {
  let {selectedId} = this.state
  return <div>
    <div id="123" className={'panel' + (selectedId === '123' ? ' open' : '')}>...</div>
    <div id="456" className={'panel' + (selectedId === '456' ? ' open' : '')}>...</div>
    ...
  </div>
}

That gets tedious to repeat if you're rendering these manually instead of based on a list of things, so you can break some of the implementation detail out into another ponent:

function Panel({children, id, open}) {
  let className = 'panel'
  if (open) className += ' open'
  return <div id={id} className={className}>{children}</div>
}

render() {
  let {selectedId} = this.state
  return <div>
    <Panel id="123" open={selectedId === '123'}>...</Panel>
    <Panel id="456" open={selectedId === '456'}>...</Panel>
    ...
  </div>
}
发布评论

评论列表(0)

  1. 暂无评论