有条件地渲染React组件

时间:2019-10-17 09:07:25

标签: javascript reactjs conditional-statements

我正在努力渲染反应成分的某些片段。这是我的组件的样子:

import XYZ from './XYZ.js';

class ABC extends React.Component{
  constructor(props, context){
    super(props, context);
      this.state = {
        showXYZ: false,
        showControl: false
      }
    }

  onshowClick = () => {
    this.setState({ showXYZ: true });
  };

  oncontrolClick = () => {
    this.setState({ showXYZ: true });
  };

  render() {
    return(
      {
        this.state.showXYZ
          ? <XYZ />
          : <div>
            <Button onClick={this.onshowClick}>SHOW</Button>
            </div> 
          <h1>Some text</h1>
          <p> More text </p>}
    )
  }
}

我也想在showControl为true时渲染相同的片段。像这样:

return(
  {
    this.state.showControl
      ? <XYZ click = {this.props.oncontrolClick} />
       <div>
        <Button onClick={this.onshowClick}>SHOW</Button>
      </div>
      <h1>Some text</h1>
      <p> More text </p> :null
  }
)

现在的问题是如何同时处理这两个问题。我尝试使用逻辑运算符,但似乎无法正常工作。

5 个答案:

答案 0 :(得分:0)

尝试如下所示的multi ternary operator

this.state.showXYZ ? <XYZ /> :  this.state.showControl ? <XYZ  click = {this.props.oncontrolClick} /> : 
  <div>
  <Button onClick={this.onshowClick}>SHOW</Button>
  </div>
  <h1>Some text</h1>
  <p> More text </p>
        <div>
           <Button onClick={this.onshowClick}>SHOW</Button>
        </div> 
       <h1>Some text</h1>
       <p> More text </p>

答案 1 :(得分:0)

您忘记将else组件包装在单个div中。使用此

<div>
  <div>
     <Button onClick={this.onshowClick}>SHOW</Button>
  </div>
  <h1>Some text</h1>
  <p> More text </p>
</div>

顺便说一句,您可以使用if条件来简化您的生活,例如:

render(){
if(this.state.showXYZ ||  this.state.showControl)
return(<XYZ click={this.state.showControl? this.props.oncontrolClick : null}/>) 

else 
{
return(
<div>
    <div>
      <Button onClick={this.onshowClick}>SHOW</Button>
    </div> 
    <h1>Some text</h1>
    <p> More text </p>
</div>
)
}


 }

答案 2 :(得分:0)

您只能从条件语句返回一个元素。将它们包装在div或React Fragment中

return(
 <div>
  {
   this.state.showControl ? <XYZ  click = {this.props.oncontrolClick} /> :
   <div>
      <div>
      <Button onClick={this.onshowClick}>SHOW</Button>
      </div>
      <h1>Some text</h1>
      <p> More text </p>
   </div>
  }
 </div>
)

答案 3 :(得分:0)

认为三元运算符只是使用||缩短了if语句。应该可以解决您的问题:

return(
  <div>
    { this.state.showControl || this.state.showXYZ 
      ? <XYZ click={this.props.oncontrolClick} /> : 
      <div>
        <Button onClick={this.onshowClick}>SHOW</Button>
      </div>
      <h1>Some text</h1>
      <p> More text </p>}
    } 
  </div>
)

答案 4 :(得分:0)

尝试一下。

 render() {
      return (
    this.state.showXYZ || this.state.showControl
      ? <XYZ click={this.state.showControl?this.props.oncontrolClick:()=>{}}/>
      : <React.Fragment><div>
        <Button onClick={this.onshowClick}>SHOW</Button>
        </div> 
      <h1>Some text</h1>
      <p> More text </p></React.Fragment>
)

}