在React上编写If条件

时间:2018-11-23 09:17:09

标签: reactjs react-native if-statement jsx

我尝试在循环内编写一个if语句,但它给出了一个错误。我尝试使用{},但它也无法正常工作,如何正确编写。

`<Option
      optionText={option}      

 colorText = {props.colors[index]}
      priceText = {props.prices[index]}
      rangeText = {props.ranges[index]}
      domainText = {props.domains[index]}

    if(this.props.colorText == this.props.domainText){
      //I want to write a if condition here but it says Identifier expected
    }
      count= {index + 1}
      handleDeleteOption={props.handleDeleteOption}
    />
    </div> 
      )) 
    }  
  </div>`

从'react'导入React;

const Option =(props)=>(

<p className="add-option-color">
  props.rangeText = {(props.colorText == props.domainText) ? props.rangeText : 
    props.domainText}
  {props.count}. Product: {props.optionText} , Color: {props.rangeText} , Price: {props.priceText}</p>


    <button  className="button button--link" onClick={(e) => {
        props.handleDeleteOption(props.optionText,props.colorText,props.priceText);
      }}
    >
      remove
    </button>
    <hr></hr>
  </div>
);

export default Option;

2 个答案:

答案 0 :(得分:2)

干净的方法是使用ternary operator,如本例所示:

<Option
      optionText={option}
      colorText = {props.colors[index]}
      priceText = {props.prices[index]}
      rangeText = {props.ranges[index]}
      domainText = {props.domains[index]}
      YOURPROPS = {(this.props.colorText == this.props.domainText) ? VALUEIFTRUE : 
      VALUEIFFALSE}
      count= {index + 1}
      handleDeleteOption={props.handleDeleteOption}
/>

答案 1 :(得分:0)

您可以调用如下函数--->

out_