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

Here i want to get the form tag if the prop boolean value is true,but its not working as expected. 如果prop boolean值为true,但在这里我想获取form标记,但是它没有按预期工作。 if i use code like this 如果我使用这样的代码

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

it comes,So if opening and closing tags are together then its working.is there any way to get the values when the tags are apart...please help 因此,如果打开和关闭标签在一起,那么它的工作原理。有什么方法可以在标签分开时获取值...请帮助

You're trying to do something, that's somewhat of an anti-pattern. 您正在尝试做某事,这有点反模式。 This might be a better solution: 这可能是一个更好的解决方案:

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

Please try Conditional Rendering 请尝试条件渲染

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

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

A different and better way to do conditional rendering 进行条件渲染的另一种更好的方法

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