简体   繁体   English

React 中的类名

[英]className in React

I've a react code as shown below in which I want to add a className at Line Z conditionally in React when Line A doesn't render anything我有一个如下所示的反应代码,其中我想在A 线不呈现任何内容时有条件地在 React 中的Z 线添加一个类名

When Line A doesn't render anything, I want to add className hide (at Line Z) (hide { display: none }) so that it can hide the entire abc-def div .Line A不呈现任何内容时,我想添加className hide (at Line Z) (hide { display: none })以便它可以隐藏整个abc-def div I found a solution from their official website but I am unable to integrate it in my code above.我从他们的官方网站上找到了一个解决方案,但我无法将它集成到我上面的代码中。

https://reactjs.org/docs/faq-styling.html#how-do-i-add-css-classes-to-components https://reactjs.org/docs/faq-styling.html#how-do-i-add-css-classes-to-components

Use inline styling with conditions as you wanted.根据需要使用带有条件的内联样式。

Instead off calling those functions inline, consider calling them before the render() function, so you can check the contents;不要在内联调用这些函数,而是考虑在render() function 之前调用它们,这样你就可以检查内容;

const renderPrograms = () => {
    return programs.map((program, index)=>{
        return (
            <a href={program.url} key={index}>
                <div className="program" >
                    <div class="hello-world">{program.name}</div>
                </div >
            </a>
        )
    })
}

const lineA = programs && renderPrograms();
const lineBClassName = (!lineA) ? ' hide' : '';

return(
    <div class="parent-div">
        <div className ="pqr-xyz">  
            <h5>Hello World</h5>            
        </div>
        <div className={"abc-def" + lineBClassName}>        
            <h5>Programs</h5>
            {lineA}
        </div>
    </div> 
)

Since programs is an array, you can check it first由于programs是一个数组,所以可以先检查一下

This is a conditional rendering solution这是一个条件渲染解决方案

return(
 <div class="parent-div">
  <div className ="pqr-xyz">  
     <h5>Hello World</h5>            
  </div>
  {programs.length && 
  <div className="abc-def hello-world">
     <h5>Programs</h5>
    {renderPrograms()}
   </div>}
 </div> 
 )

Conditional class solution有条件的class解决方案

return(
 <div class="parent-div">
  <div className ="pqr-xyz">  
     <h5>Hello World</h5>            
  </div>
  // if the length is 0 or the array is empty then add hide class
  <div className={`abc-def ${!programs.length && "hide"}`}>
     <h5>Programs</h5>
    {programs.length && renderPrograms()}
   </div>
 </div> 
 )

Anyway, You can also check classnames library, it's more effective way to add conditional class in react无论如何,您也可以检查名库,这是在反应中添加条件 class 更有效的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM