在react.js中相当于ng-if的是什么?

时间:2016-04-21 13:25:25

标签: reactjs

我正在使用角度做出反应,我试图找出一个很好的反应替代角度的ng-if指令,我根据条件渲染或不渲染元素。以此代码为例。我使用的是打字稿(tsx)顺便说一句,但这不重要。

"use strict";

import * as React from 'react';

interface MyProps {showMe: Boolean}
interface MyState {}

class Button extends React.Component <MyProps, MyState>{
  constructor(props){
    super(props);
    this.state = {};
  }

  render(){
    let button;
    if (this.props.showMe === true){
       button = (
        <button type="submit" className="btn nav-btn-red">SIGN UP</button>
      )
    } else {
      button = null;
    }
    return button;

}
}
export default Button;

这个解决方案有效,但还有另一种方法可以实现这种效果吗?我只是在猜测

14 个答案:

答案 0 :(得分:54)

ternary operator怎么样?

render() {
  return (
    this.props.showMe ? <button type="submit" className="btn nav-btn-red">SIGN UP</button> : null
  );
}

答案 1 :(得分:15)

我出于历史目的将此留在此处,请参阅下面的编辑,以便在反应开发一段时间后获得更好的解决方案 我最终创建了一个NgIf组件(这是反应原生但可能有效反应)

代码:

import React, {Component} from "react";

class NgIf extends Component {
  render() {
    if (this.props.show) {
      return (
        this.props.children
      );
    } else {
      return null
    }
  }
}

export default NgIf;

用法:

...
import NgIf from "./path/to/component"
...

class MyClass {
   render(){
      <NgIf show={this.props.show}><Text>This Gets Displayed</Text></NgIf>
   }
}

我是新手,所以可以改进,但帮助我从Angular过渡

修改

一旦我获得了更多经验,请参阅下面的修改以获得更好的解释 <击>

<击>

感谢周杰伦的评论,一个好主意也是:

render() {
   <View>{this.props.value ? <Text>Yes</Text> : <Text>No</Text>}</View>
}

OR

render() {
   <View>{this.props.value && <Text>Yes</Text>}</View>
}

与其他一些答案类似但是内联工作,而不是使用整个渲染块/函数,不需要特殊组件,并且可以使用带有三元运算符的else语句。 if语句中包含的项目如果父对象不存在则不会抛出错误。即如果props.value不存在,则props.value.value2不会抛出错误。

查看此答案https://stackoverflow.com/a/26152067

编辑2:

根据上述链接(https://stackoverflow.com/a/26152067)以及在开发反应应用程序的更多经验之后,上述方式并非最佳方式。

反应中的条件操作员实际上很容易理解。有两种方法可以做:

//Show if someItem
{someItem && displayThis}

//Show if else
{someItem ? displayThisIfTrue : displayThisIfFalse}

如果“someItem”不是布尔表达式,您可能会遇到一个警告。如果说0反应将打印0或反应原生将给你一个错误需要在文本元素中包装“0”。对于虚假测试来说,这通常不是问题,但是会给真正的测试带来问题。例如:

{!someItem && displayThis} //Will work just fine if item is 0 or null or "" etc
{someItem && displayThis} //Will print the value of someItem if its not falsy

我经常使用的技巧?双重否定。

{!!someItem && displayThis}

请注意,这不适用于三元运算符(myVar?true:false),因为它会隐式将结果转换为布尔表达式。

答案 2 :(得分:8)

如果你还有其他元素,你可以像这样包装条件:

render() {
  return (
    <div>Stuff</div>
    {this.props.showMe && (
      <button type="submit" className="btn nav-btn-red">SIGN UP</button>
    )}
    <div>More stuff</div>
  );
}

答案 3 :(得分:7)

更好一点:

render() {
  return (
    this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>
  );
}

答案 4 :(得分:2)

我可以想到至少三种不同的方法来模拟React

中的ng-if功能
  • 如果
  • 开关
  • IIFE(立即调用的函数表达式)

您可以在此处阅读帖子:Angular's ng-if Equivalent In a React Component

基本上,你想做这样的事情:

var IfDemoComponent = React.createClass({
  render: function() {
    var el = null;
    if (this.props.showMe) {
      el = (
        <div>
          I am only included in the DOM if this.props.showMe evaluates to true.
        </div>
      );
    }
   return el;
  }
});

答案 5 :(得分:2)

我只想添加*ngIf in angular不会实例化它所附加的组件。在React中,如果在return语句中使用if语句,则即使未显示该组件,它仍将实例化该组件。要在React中实现真正的*ngIf类型行为,您必须创建一个包含return语句之外的条件组件的变量:

render() {

  const show = false

  return (
    if (show) {
       <AwesomeComponent />   //still instantiated
    }
  )
}

render() {

  let c = null
  const show = false

  if (show) {
    c = <AwesomeComponent />   //not instantiated
  }
  return (
    c
  )
}

答案 6 :(得分:1)

  

falsenullundefinedtrue是有效的孩子。他们根本就没有   渲染。这些JSX表达式将呈现相同的东西:

所以你可以试试这个

const conditional=({condition,someArray})=>{
     return(
        <div>
          {condition && <Header /> // condition being boolean} 
          {someArray.length>0 && <Content />}
        </div>
      )
}

这对于有条件地渲染React元素很有用。此JSX仅呈现if条件为true 并且仅在someArray.length> 0

时呈现

答案 7 :(得分:1)

我不喜欢代码中有很多三元运算符。这就是为什么我用一些有用的组件创建一个库。 &#34; RCIF&#34;

  <RcIf if={condition} >
    <h1>I no longer miss ngif</h1>
  </RcIf>
  <RcIf if={othercondition} >
    <h1>I no longer miss v-if</h1>
    <RcElse>
      <h1>I love react</h1>
    </RcElse>
  </RcIf>

您可以从npm

安装它

https://www.npmjs.com/package/rc-if

答案 8 :(得分:1)

我也来自有角度的背景,并且正在寻找一种简单的衬纸来显示变量是否包含任何元素的标签。这对我有用:

re.findall

答案 9 :(得分:0)

我是Tersus-jsx.macro的创建者,我认为该模块提供了该问题的确切条件。

此宏允许使用与AngularJS for React JSX中相同的方式来处理事务,而不是混合JSX表达式和ES6来实现ng-if或ng-repeat。对于ng-if:

<div>
  <button
    tj-if={a === 0}
    id="gotoA"
    className="link"
    onClick={clicking}
  />
</div>

等效于

<div>
  {(a === 0) && (
    <button
      id="gotoA"
      className="link"
      onClick={clicking}
    />
  )}
</div>

考虑到开箱即用的最新版本的create-react-app支持Babel-Macro,您需要做的就是npm安装此模块,用“ tersus”包装渲染返回并开始分配这些道具。

您可以从以下位置安装它: https://www.npmjs.com/package/tersus-jsx.macro

答案 10 :(得分:0)

我只是创建了一个将expresting和另外两个自变量作为模板的方法,以防表达式true,另一个是选项else模板

var match =  str.match(/_([20|19].+)_day/i);

我这样使用

export function rif(exp, template, elseTemplate = null) {
    if (exp) {
        return template;
    } else {
        return elseTemplate;
    }
}

答案 11 :(得分:0)

我个人喜欢使用吸气剂,它很干净而且可以确保反应性:

get toBeDisplayed(){
  const { someLogicState } = this.state;
  if(someLogicState)
    return (
      <div>
        Hi, world !
      </div>
    );
  else
    return null;
}

render(){
  return (<div>{this.toBeDisplayed}</div>);
}

答案 12 :(得分:0)

我正在努力工作并做出反应。我认为angular通过不同的指令很好地管理了逻辑条件。

reactjs中,这种方法的工作方式不同。

您可以将if else条件用作returnrender function中的ternary operator

如果有的话

  render(){
    
    const auth = true;
    
    if(!auth)
      return(
      <div className="ps-checkout__login">
        <div className="d-flex flex-row">
            <div className="p-2"><img src="../../../static/img/return-customer.png"></img> 
             Returning Customer?</div>
            <div className="p-2"> 
                <Link href="/account/login">
                    <a>                            
                        Click here to login
                    </a>
                </Link>
            </div>
        </div>
    </div>
    )
  else return null;
    }

使用三元运算符

{ auth?
    (<div className="ps-checkout__login">
        <div className="d-flex flex-row">
            <div className="p-2"><img src="../../../static/img/return-customer.png"></img> 
            Returning Customer?</div>
            <div className="p-2"> 
                <Link href="/account/login">
                    <a>                            
                        Click here to login
                    </a>
                </Link>
            </div>
        </div>
    </div>):null } 

答案 13 :(得分:0)

来自 React 文档

https://reactjs.org/docs/conditional-rendering.html

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
  <Mailbox unreadMessages={messages} />,
  document.getElementById('root')
);