简体   繁体   English

添加显示以有条件地反应组件?

[英]adding display to react component conditionally?

I am trying to hide the components conditionally我试图有条件地隐藏组件

method 1: to add style = display: none to div方法一:给div添加style=display:none

is there a way to dynamically add display to div via state?有没有办法通过state动态添加显示到div?

since all the components are in Div, how to isolate each rendered component and add display none?既然所有组件都在Div中,如何隔离每个渲染组件并添加不显示?

is there a way to add the state that can trigger css / add css to certain react component?有没有办法添加可以触发 css 的 state / 将 css 添加到某些反应组件?

import React, { Component } from 'react';
import all the component A, B AND C

class App extends Component {
   constructor(props) {
     super(props);
    this.state = {};
  }
  

  render() {
    return (
      <div>
               <Component A/>
               <Component B/>
              <Component C/>

      </div>
    );
  }
}

export default App;

This seems like partly a duplicate of this question .这似乎部分是这个问题的重复。

You can set your values of a class dynamically like this:您可以像这样动态设置 class 的值:

renter() { 
  return (
    <div className={is_displayed ? "showItClassName" : "dontShowItClassName"} > 
      ...
    </div>
  );

This is probably the better way because you can re-use your css classes.这可能是更好的方法,因为您可以重新使用 css 类。 You can create variables ahead of time with the class name or call a function if you don't want the conditional in the middle of the html tag.您可以使用 class 名称提前创建变量,或者如果您不希望 html 标记中间的条件,则调用 function。

If your sure you want to use an style tag you need the extra curly braces.如果您确定要使用样式标签,则需要额外的花括号。

render() {
  return (
    <div style={is_displayed ? {display:"block"}: {display:"none"}} >
           <Component A/>
           <Component B/>
          <Component C/>

    </div>
  );

Per Choosing the Type at Runtime :根据在运行时选择类型

import { ComponentA } from './ComponentA';

<div>
  {(() => {
    // capitalized variable first
    let Component = <p>Error!</p>;
    if (/google/.test(this.state.url)) {
      Component = ComponentA
    }
    return <Component />
  })()}
</div>

You can render the component conditionally instead of tto use css to make this:您可以有条件地渲染组件而不是使用 css 来实现:

{true_condition && ( <Component /> )}

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

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