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