簡體   English   中英

條件渲染無法按預期在reactjs中工作

[英]Conditional rendering is not working as expected in reactjs

 function Demo(props){ return( <div> {props.boolean && <div>} <h1> HI,many of these kind of dom elements will be here </h1> {props.boolean && </div>} </div> ) } ReactDOM.render( <Demo boolean="true"/>, document.body ); 
 <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <!DOCTYPE html> </head> <body> </body> </html> 

如果prop boolean值為true,但在這里我想獲取form標記,但是它沒有按預期工作。 如果我使用這樣的代碼

   {props.boolean && <div></div>}  
    <h1>
        HI,many of these kind of dom elements will be here
     </h1>
    {props.boolean && <div></div>}

因此,如果打開和關閉標簽在一起,那么它的工作原理。有什么方法可以在標簽分開時獲取值...請幫助

您正在嘗試做某事,這有點反模式。 這可能是一個更好的解決方案:

function Demo(props) {
    function MyContents() {
        return (
            <h1>
                HI,many of these kind of dom elements will be here
            </h1>
        );
    }

    return (
        <div>
            { props.boolean ?
                <div><MyContents /></div>
                :
                <MyContents />
            };
        </div>
    );
}

ReactDOM.render(
    <Demo boolean="true" />, document.body
);

請嘗試條件渲染

function Demo(props) {
    const flag = props.flag;
    return (
        if (flag) {
            return <h1 > true < /h1>;
        }

        return <h1 > false < /h1>;

    )
}

 ReactDOM.render(
  <Demo flag={true}/>,  document.getElementById('root')
);

的HTML

<body>
  <div id="root"></div>
</body>

進行條件渲染的另一種更好的方法

function Demo(props) {
    return (
      <h1>{props.flag ? true : false}</h1>;
    )
}

 ReactDOM.render(
  <Demo flag={true}/>,  document.getElementById('root')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM