ng-if in react.js에 해당하는 것은 무엇입니까?
저는 각도를 사용하여 반응하게 되었습니다. 그리고 조건에 따라 요소를 렌더링하거나 렌더링하지 않는 각도 ng-if 지시어의 좋은 반응 방법을 찾고 있습니다.이 코드를 예로 들어 보겠습니다.저는 (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;
이 솔루션은 효과가 있지만 일반적으로 이 효과를 얻기 위해 사용되는 다른 방법이 있습니까?그냥 추측일 뿐이야
3진 연산자는 어때?
render() {
return (
this.props.showMe ? <button type="submit" className="btn nav-btn-red">SIGN UP</button> : null
);
}
이 경우에도 하실 수 있습니다.&&
:
render() {
return (
this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>
);
}
큰를 JSX로 할 수 .()
s:
render() {
return this.props.showMe && (
<div className="container">
<button type="submit" className="btn nav-btn-red">
SIGN UP
</button>
</div>
);
}
또한 인라인:
render() {
return (
<div className="container">
{this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>}
</div>
);
}
이 내용은 이력 목적으로 남겨두겠습니다.잠시 후 리액션을 진행하여 보다 나은 솔루션을 얻으려면 아래의 편집 내용을 참조해 주십시오.
결국 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로부터의 이행에 도움이 됩니다.
편집
더 많은 경험을 쌓은 후 자세한 설명은 아래 편집을 참조하십시오.
아래 Jay의 코멘트 덕분에 좋은 아이디어는 다음과 같습니다.
render() {
<View>{this.props.value ? <Text>Yes</Text> : <Text>No</Text>}</View>
}
또는
render() {
<View>{this.props.value && <Text>Yes</Text>}</View>
}
다른 응답과 비슷하지만 전체 렌더 블록/함수를 사용하는 대신 인라인 방식으로 작동합니다. 특별한 구성 요소가 필요하지 않으며 3진 연산자와 함께 else 문을 사용할 수 있습니다.또한 if 문에 포함된 항목은 상위 개체가 존재하지 않는 경우에도 오류를 발생시키지 않습니다. if if if 의 ieprops.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}
이것은 결과를 암묵적으로 부울식으로 변환하기 때문에 3진 연산자(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>
);
}
그 싶었다.*ngIf
.[ React ] [React ]에서 if 을 사용하는 경우 []에서 [React]를 합니다.return
스테이트먼트에서는 컴포넌트가 표시되지 않아도 인스턴스화 됩니다. 것을 *ngIf
을 type behavior의 하는 변수를 . 조건 구성요소를 고정하는 변수를 생성해야 합니다.return
★★★★★★★★
render() {
const show = false
return show
? <AwesomeComponent /> //still instantiated
: null
}
render() {
let c = null
const show = false
if (show) {
c = <AwesomeComponent /> //not instantiated
}
return c
}
조금 더 친절하게:
render() {
return (
this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>
);
}
리액트에서 ng-if 기능을 시뮬레이트하는 방법은 적어도3가지 생각할 수 있습니다.
- 한다면
- 전환하다
- IIPE(즉시 호출된 함수 표현)
글은 이쪽에서 보실 수 있습니다: 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;
}
});
false
,null
,undefined
, , , , 입니다.true
유효한 아이입니다.그들은 단순히 렌더링하지 않는다.이러한 JSX 표현식은 모두 같은 것으로 렌더링됩니다.
그러니까 이거 한번 해봐
const conditional=({condition,someArray})=>{
return(
<div>
{condition && <Header /> // condition being boolean}
{someArray.length>0 && <Content />}
</div>
)
}
이것은 React 요소를 조건부로 렌더링하는 데 유용할 수 있습니다.이 JSX는 조건이 true인 경우에만 렌더링하며 someArray.length>0인 경우에만 렌더링합니다.
나는 코드에 많은 삼원 연산자가 있는 것을 좋아하지 않는다.그래서 유용한 부품 몇 개로 도서관을 만들었어요."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>
설치는 npm부터 가능합니다.
https://www.npmjs.com/package/rc-if
저도 각진 배경에서 왔고 변수가 요소를 가지고 있다면 태그를 보여줄 간단한 라이너를 찾고 있었습니다.이 방법은 효과가 있었습니다.
<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>
저는 Tersus-jsx.macro의 작성자입니다.이 모듈에서는 이 질문에 필요한 정보를 정확하게 제공하고 있다고 생각합니다.
JSX 식과 ES6를 혼합하여 ng-if 또는 ng-repeat를 달성하는 대신, 이 매크로는 Angular에서와 같은 방식으로 작업을 수행할 수 있습니다.반응 JSX용 JS. 예를 들어 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 에서 실시할 수 있습니다.
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')
);
개인적으로 저는 게터를 사용하는 것을 좋아합니다. 깨끗하고 반응성을 보장합니다.
get toBeDisplayed(){
const { someLogicState } = this.state;
if(someLogicState)
return (
<div>
Hi, world !
</div>
);
else
return null;
}
render(){
return (<div>{this.toBeDisplayed}</div>);
}
표현식 true와 다른 두 개의 인수를 템플릿으로 사용하는 메서드를 만듭니다.
export function rif(exp, template, elseTemplate = null) {
if (exp) {
return template;
} else {
return elseTemplate;
}
}
그리고 이렇게 씁니다.
import { rif } from '../utilities';
...
render() {
return (
<main role="main" className="container">
{rif(
this.movies.length > 0,
<p>Showing {this.movies.length} movies. </p>,
<p>There are no movies..</p>
)}
</main>
);
}
나는 각도와 리액션을 동시에 하고 있다.생각합니다angular
다양한 지시를 통해 논리적인 조건을 적절하게 관리합니다.
인reactjs
이 접근방식은 다른 방법으로 동작합니다.
사용할 수 있습니다.if else
로서 조건짓다.return
의render 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 }
언급URL : https://stackoverflow.com/questions/36771017/what-is-the-equivalent-to-ng-if-in-react-js
'programing' 카테고리의 다른 글
UI 라우터를 사용하여 현재 상태 이름 노출 (0) | 2023.03.23 |
---|---|
Spring Crud Repository를 사용한 대소문자를 구분하지 않는 쿼리 (0) | 2023.03.23 |
여러 워크시트를 사용하여 PHPexcel 기존 .xlsx 파일 수정 (0) | 2023.03.23 |
angularjs 1.6.0(지금으로 변경) 루트가 기능하지 않음 (0) | 2023.03.23 |
onFocus 및 onBlur가 반응으로 렌더링되지 않음 (0) | 2023.03.23 |