如果条件反应

时间:2016-11-29 19:44:34

标签: javascript reactjs

如果条件在reactjs中不起作用。想要创建一个轮播,以使其第一个图像包含“活动”类,而其他图像则不包含。

条件是索引是否为零

如果条件反应如何申请

class CaseImages extends React.Component {
  constructor() {
    super();
  }

  _getImages() {
    return this.props.images.map((image, index) => 
                                 if ({index}==0}<div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>}
                                else{
                                 <div className="item" key={index}><img src={image.url} class="case-image"/ ></div>
                                 }
                                );
}
	render(){
		return(
		<div className="row">
			<div className="col-xs-12 col-sm-12">
				<div className="case-feature-image">
					<div id="myCarousel" className="carousel slide" data-ride="carousel">
                        <div className="carousel-inner" role="listbox">
                                {this._getImages()}
                        </div >
      <a className ="left carousel-control" href ="#myCarousel" role ="data-slide = "prev">
      <span className = "glyphicon glyphicon-chevron-left"
      aria - hidden = "true"> </span>
                            <span className="sr-only">Previous</span>
      </a>
                        <a className="right carousel-control" href="#myCarousel" role="button" data-slide="next">
                            <span className="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      <span className ="sr-only"> Next </span>
                        </a>
      </div>
				</div>
      </div>
		</div>
    )
  };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

3 个答案:

答案 0 :(得分:1)

尝试类似以下的内容:

<div className={index === 0 ? 'item active' : 'item'}>...</div>

您还可以使用函数计算正确的类:

// this function needs to live *outside* of JSX
function getClasses(index) {
  return 'item' + index === 0 ? ' active' : '';
}

// this is in the JSX
<div className={getClasses(index)}>...</div>

答案 1 :(得分:0)

您可以使用条件运算符,如下所示:

{index===0? 
    <div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>
:
    <div className="item" key={index}><img src={image.url} class="case-image"/ ></div>
}

或像这样的函数:

{(()=> {     
       if(index===0){
           return(<div className="item active" key={index}><img src={image.url} class="case-image"/ ></div>);}
       else{
           return(<div className="item" key={index}><img src={image.url} class="case-image"/ ></div>);}             
       })()}

答案 2 :(得分:0)

我将使用classnames

向帽子中添加另一个替代品
const divClass = classNames('item', { active: index === 0 })
...
<div className={divClass} key={index}>
  <img src={image.url} className="case-image" />
</div>

我更喜欢在标签之外包装计算,并尽可能去重复。