programing

만약...엘세...을 사용할 수 있습니까?리액트 렌더 함수에 있는 문?

javajsp 2023. 3. 10. 21:05

만약...엘세...을 사용할 수 있습니까?리액트 렌더 함수에 있는 문?

컴포넌트,즉 리액트 컴포넌트가 .render() (하지 않습니다.)

render(){
    return (
        <div>
            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

        </div>
    )
}

꼭 그렇지는 않지만, 해결 방법이 있습니다.React 문서에는 조건부 렌더링에 대한 섹션이 있으므로 살펴봐야 합니다.다음은 인라인 if-else를 사용하여 수행할 수 있는 작업의 예입니다.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

jsx를 반환하기 전에 렌더링 함수 내에서 처리할 수도 있습니다.

if (isLoggedIn) {
  button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
  button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
  <div>
    <Greeting isLoggedIn={isLoggedIn} />
    {button}
  </div>
);

ZekeDroid 。있을 하지 않은 않은 는, 「」, 「」를 사용할 수 .&& operator.

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

실제로 OP가 요구하는 대로 정확하게 실행하는 방법이 있습니다.다음과 같이 어나니머스 함수를 렌더링하고 호출합니다.

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}

4가지 조건부 렌더링 방법

(기능 컴포넌트의 반환문 또는 클래스 컴포넌트의 렌더 함수의 반환문)

 

삼항 연산자

 

return (
    <div>     
        {
            'a'==='a' ? <p>Hi</p> : <p>Bye</p>
        } 
    </div>
)

주의: 조건이 충족될 경우에만'a'==='a' 말이다.<p>Hi</p>화면에 렌더링됩니다. 않으면, 「」가 됩니다.<p>Bye</p>화면에 렌더링됩니다.

 

논리 연산자

 

리 and 。&&

return (
    <div>     
        {
            'a'==='a' && <p>Hi</p>
        } 
    </div>
)

주의: 조건이 충족될 경우에만'a'==='a' 말이다.<p>Hi</p>화면에 렌더링됩니다.

 

★★★||

export default function LogicalOperatorExample({name, labelText}) {
    
  return (
    <div>       
         {labelText || name}      
    </div>
  )
}

주의: 만약labelText ★★★★★★★★★★★★★★★★★」name두 가지 소품이 .labelText화면에 렌더링됩니다. 그 중 .name ★★★★★★★★★★★★★★★★★」labelText되며, 가 소품으로 전달되면, 통과한 소품이 화면에 렌더링됩니다.

 

if, other, other, if.

 

return ( 
        <div>     
            {
                (() => {
                    if('a'==='b') {
                            return (
                                <p>Hi</p>
                            )
                        } else if ('b'==='b') {
                            return (
                            <p>Hello</p>
                            )
                        } else {
                            return (
                                <p>Bye</p>
                            )
                        }
                })()  
            }  
        </div>  
    )

주의: 익명 함수를 사용해야 합니다(또한 함수를 즉시 호출해야 합니다).

 

스위치 스테이트먼트

 

return ( 
    <div>     
        {
            (() => {
                switch(true) {
                        
                    case('a'==='b'): {
                            return (
                                <p>Hello</p>
                            )
                        }
                    break;
                        
                    case('a'==='a'): {
                        return (
                            <p>Hi</p>
                        )
                    }
                    break;
                    
                    default: {
                            return (
                                <p>Bye</p>
                            )
                        }
                    break;
                    }
            })()  
        }  
    </div>  
)

주의: 익명 함수를 사용해야 합니다(또한 함수를 즉시 호출해야 합니다).

수 요.conditional「」와 같은 문.if,else:

 render() {
    const price = this.state.price;
    let comp;

    if (price) {

      comp = <h1>Block for getting started with {this.state.price}</h1>

    } else {

      comp = <h1>Block for getting started.</h1>

    }

    return (
      <div>
        <div className="gettingStart">
          {comp}
        </div>
      </div>
    );
  }

1 형 11: If 스타일

{props.hasImage &&

  <MyImage />

}


2 입 22: If else 스타일

   {props.hasImage ?

      <MyImage /> :

      <OtherElement/>

    }

TERNARY 연산자에 대해 기억해야 합니다.

:

그래서 네 코드는 이렇게 될 거야

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // note: code does not work here
            { 
               this.props.hasImage ?  // if has image
               <MyImage />            // return My image tag 
               :
               <OtherElement/>        // otherwise return other element  

             }
        </div>
    )
}

여러 가지 조건이 필요한 경우 이 기능을 사용해 보십시오.

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

if else 구조의 약어는 JSX에서 예상대로 작동합니다.

this.props.hasImage ? <MyImage /> : <SomeotherElement>

DevNacho 블로그 포스트에서 다른 옵션을 찾을 수 있지만, 속기로 하는 것이 일반적입니다.더 큰 if 절이 필요한 경우 반환되는 함수 또는 컴포넌트 A 또는 컴포넌트 B를 작성해야 합니다.

예를 들어 다음과 같습니다.

this.setState({overlayHovered: true});

renderComponentByState({overlayHovered}){
    if(overlayHovered) {
        return <OverlayHoveredComponent />
    }else{
        return <OverlayNotHoveredComponent />
    }
}

오버레이를 파괴할 수 있습니다.파라미터로 지정하면 이.state에서 정지합니다.그런 다음 해당 함수를 render() 메서드로 실행합니다.

renderComponentByState(this.state)

요소를 표시하는 조건을 원하는 경우 다음과 같은 기능을 사용할 수 있습니다.

renderButton() {
    if (this.state.loading) {
        return <Spinner size="small" spinnerStyle={styles.spinnerStyle} />;
    }

    return (
        <Button onPress={this.onButtonPress.bind(this)}>
            Log In
        </Button>
    );
}

그런 다음 렌더링 함수 내부의 도움말 메서드를 호출합니다.

<View style={styles.buttonStyle}>
      {this.renderButton()}
</View>

아니면 다른 방법으로 반품할 수도 있습니다.

{this.props.hasImage ? <element1> : <element2>}

두 개의 다른 종속성이 있는 경우 조건부 연산자 내에서 조건부(삼진수) 연산자를 사용할 수도 있습니다.

{
(launch_success)
  ?
  <span className="bg-green-100">
    Success
  </span>
  :
  (upcoming)
    ?
    <span className="bg-teal-100">
      Upcoming
    </span>
    :
    <span className="bg-red-100">
      Failed
    </span>
}

많은 훌륭한 답변이 있지만 다른 뷰에 매핑하기 위해 개체를 사용하는 것을 본 적이 없습니다.

const LOGS = {
  info: <Info />,
  warning: <Warning />,
  error: <Error />,
};
 
const Notification = ({ status }) => <div>{LOGS[status]}</div>

3진 연산자를 사용했는데 잘 작동하고 있어요.

{item.lotNum == null ? ('PDF'):(item.lotNum)}

어느 대답도 단락 방법에 대해 언급하지 않았습니다.

{this.props.hasImage && <MyImage />}

다른 로직으로 렌더링할 경우 사용할 수 없습니다.는 이에 대해 사례로 배웠다.

좀 더 자세히 스캔하면 @ZekeDroid의 코멘트를 볼 수 있지만, 도움이 될 수 있기 때문에 이 코멘트를 드롭합니다.

내가 여기 너무 늦은 것 같아.하지만 이게 누군가에게 도움이 되었으면 좋겠어요.먼저 이 두 가지 요소를 분리합니다.

renderLogout(){
<div>
   <LogoutButton onClick={this.handleLogoutClick} />
<div>
}

renderLogin(){
<div>
   <LoginButton onClick={this.handleLoginClick} />
<div>
}

그런 다음 if else 문을 사용하여 렌더 함수에서 이러한 함수를 호출할 수 있습니다.

render(){
if(this.state.result){
  return this.renderResult();
}else{
  return this.renderQuiz();
}}

난 이거면 돼.:)

스위치 케이스 또는 3진 연산자를 사용해 보십시오.

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // updated code works here
            {(() => {
                        switch (this.props.hasImage) {
                            case (this.props.hasImage):
                                return <MyImage />;
                            default:
                                return (
                                   <OtherElement/>; 
                                );
                        }
                    })()}
        </div>
    )
}

이것은 나에게도 효과가 있었고 당신에게도 효과가 있을 것입니다.3진 연산자 시도

If를 사용하는 경우, else를 사용하는 경우, else를 사용하는 경우 이 방법을 사용합니다.

           {this.state.value === 0 ? (
                <Component1 />
            ) : this.state.value === 1 ? (
              <Component2 />
            ) : (
              <Component3 />
            )}

div 요소를 반환하고 반환 내부를 호출하는 별도의 메서드를 도입할 수 있습니다.예를 들어, 다음과 같이 상태에 따라 오류 렌더링이 달라지는 경우에 사용합니다.

const renderError = () => {
    if (condition)
        return ....;
    else if (condition)
        return ....;
    else if (condition)
        return ....;
    else
        return ....;
}

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

의 줄임말입니다.

 { condition ? <Element1/> : null }

예, JSX 렌더에서 조건을 사용할 수 있습니다.여기서 더 읽을 수 있습니다.

구문:

condition ? exprIfTrue : exprIfFalse

조건문은 다음과 같아야 합니다.다음은 예를 제시하겠습니다.

return (
    <div>
      {condition  ? (
        //do some actions if condition is true
      ) : (
        //do some actions if condition is false
      )}
    </div>
)

2개 이상의 조건이 있는 곳에서 렌더링하는 경우 인라인 이외에는 이 솔루션을 본 적이 없는 것 같습니다.그래서 공유하겠습니다.

{variable == 0 ?
  <Element1/>
:variable == 1 ?
  <Element2/>
:variable == 2 ?
  <Element3/>
:
  <Element4/>
}

나는 if-else를 갖는 것보다 내가 생각하는 해결책이 더 낫다는 것을 알았다.대신, 2개의 반품 명세서가 있습니다.예를 참조해 주세요.

render() {
    const isLoggedIn = this.state.isLoggedIn;

    if (isLoggedIn) {
        return <LogoutButton onClick={this.handleLogoutClick} />
    }

    // This will never occur if the user is logged in as the function is returned before that.
    return <LoginButton onClick={this.handleLoginClick} />
}

이것은 반환문에 if-else 또는 ternary 연산자가 있는 것보다 덜 복잡합니다.

If 스테이트먼트 컴포넌트도 작성 가능합니다.제 프로젝트에서 사용하는 것은 다음과 같습니다.

컴포넌트/IfStatement.tsx

import React from 'react'

const defaultProps = {
    condition: undefined,
}

interface IfProps {
    children: React.ReactNode
    condition: any
}

interface StaticComponents {
    Then: React.FC<{ children: any }>
    Else: React.FC<{ children: any }>
}

export function If({ children, condition }: IfProps): any & StaticComponents {
    if (React.Children.count(children) === 1) {
        return condition ? children : null
    }

    return React.Children.map(children as any, (element: React.ReactElement) => {
        const { type: Component }: any = element

        if (condition) {
            if (Component.type === 'then') {
                return element
            }
        } else if (Component.type === 'else') {
            return element
        }

        return null
    })
}

If.defaultProps = defaultProps

export function Then({ children }: { children: any }) {
    return children
}

Then.type = 'then'

export function Else({ children }: { children: any }) {
    return children
}

Else.type = 'else'

If.Then = Then as React.FC<{ children: any }>
If.Else = Else as React.FC<{ children: any }>

export default If

사용 예:

<If condition={true}>
   <If.Then>
        <div>TRUE</div>
   </If.Then>
   <If.Else>
        <div>NOT TRUE</div>
   </If.Else>
</If>

다음 경우에만:

{condition1 && 
(<div> condition1 true </div>)}

if 및 other의 경우:

{condition1 ? 
(<div> condition1 true </div>)
:(<div> condition1 false </div>)}

if, other if, other:

{condition1 ? 
(<div>condition1 true</div>)
:(condition2) && 
(<div>condition2 true</div>)
:(<div>both conditions false</div>)}

아래 코드는 If condition on react in side return에 사용할 수 있습니다.

                                    {(() => {if (true) {return ( <div><Form>
                                        <Form.Group as={Row} style={{ marginLeft: '15px', marginRight: '15px', marginBlock: '0px' }} >
                                            <Form.Label className="summary-smmdfont" style={{ flex: '1 0 auto', marginBlock: '0px' }}>   uyt</Form.Label>
                                            <Form.Label className="summary-smmdfont"style={{ textAlignLast: 'Right', flex: '1 0 auto', marginBlock: '0px' }}>
                                                09</Form.Label>
                                        </Form.Group>
                                        </Form>

                                    </div>);
                    }})()}

[...else if], 그렇지 않으면 React return 함수에서 두 번 이상 체크하려면?

{Element1? (<Element1/>) : Element2 ? (<Element2/>) : Element3 ? (<Element3/>) : Element... ? (<Element.../>) : (<ElementLast />)}

언급URL : https://stackoverflow.com/questions/40477245/is-it-possible-to-use-if-else-statement-in-react-render-function