code

react.js의 ng-if에 해당하는 것은 무엇입니까?

codestyles 2020. 12. 24. 23:44
반응형

react.js의 ng-if에 해당하는 것은 무엇입니까?


나는 angular를 사용하여 반응하기 위해오고 있으며 조건에 따라 요소를 렌더링하거나 렌더링하지 않는 angular의 ng-if 지시문에 대한 좋은 반응 대안을 찾으려고합니다. 예를 들어이 코드를 사용하십시오. 나는 typescript (tsx) btw를 사용하고 있지만 그다지 중요하지 않습니다.

"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;

이 솔루션은 작동하지만 일반적으로이 효과를 달성하는 데 사용되는 다른 방법이 있습니까? 나는 그냥 추측


방법에 대한 삼항 연산자 ?

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

나는 역사적인 목적으로 여기에 남겨두고 있습니다. 한동안 반응에서 개발 한 후 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>
   }
}

Im이 처음이므로 아마도 개선 될 수 있지만 Angular에서 전환하는 데 도움이됩니다.

편집하다

더 많은 경험이 있으면 더 나은 설명을 위해 아래 편집을 참조하십시오.

아래의 Jay 's Comment 덕분에 좋은 아이디어도 있습니다.

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

또는

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

다른 답변 중 일부와 비슷하지만 전체 렌더 블록 / 함수를 사용하는 대신 인라인으로 작동하며 특별한 구성 요소가 필요하지 않으며 삼항 연산자와 함께 else 문을 사용할 수 있습니다. if 문에 포함 된 Plus 항목은 부모 개체가없는 경우 오류를 발생시키지 않습니다. 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 인 경우 react는 0을 인쇄하거나 react native는 텍스트 요소에서 "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) 에는 적용되지 않습니다 .


다른 요소도있는 경우 다음과 같이 조건부 만 래핑 할 수 있습니다.

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

조금 더 좋습니다.

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

React에서 ng-if 기능을 시뮬레이션하는 적어도 세 가지 방법을 생각할 수 있습니다.

  • 만약
  • 스위치
  • IIFE (즉시 호출 된 함수 표현)

여기에서 게시물을 읽을 수 있습니다 : Angular의 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;
  }
});

나는 *ngIfangular에서 그것이 연결된 구성 요소를 인스턴스화하지 않는다는 것을 추가하고 싶었 습니다. React에서 문 내에서 if 문을 사용하면 return표시되지 않더라도 구성 요소를 인스턴스화합니다. *ngIfReact에서 진정한 유형 동작 을 달성하려면 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
  )
}

false, null, undefined, and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:

So you can try this

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

this can be useful to conditionally render React elements. This JSX only renders a if condition is true and will render only if someArray.length>0


I do not like having many ternary operators in the code. That's why I made a library with a couple of useful components. "RcIf"

  <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>

You can install it from npm

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


I'm coming from an angular background as well and was looking for a simple one liner to show the tag if the variable had any elements. This worked for me:

<div className="comic_creators">
    {c.creators.available > 0 ? <h4>Creators</h4> : null }
    {c.creators.items.map((creator,key) =>
        <Creator creator={creator} key={key}></Creator>
    )}
</div>

I am the creator of the Tersus-jsx.macro and I think this module provides exactly what is needed for this question.

Rather than mixing JSX expressions and ES6 to achieve ng-if or ng-repeat, this macro allows doing things the same way as in AngularJS for React JSX, e.g. for ng-if:

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

which is equivalent to

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

Given that the latest version of create-react-app support Babel-Macro out of the box, all you need to do is npm install this module, wrap the render return with "tersus" and start assigning those props.

You can install this from: https://www.npmjs.com/package/tersus-jsx.macro

ReferenceURL : https://stackoverflow.com/questions/36771017/what-is-the-equivalent-to-ng-if-in-react-js

반응형