简体   繁体   English

通过ID获取HTML元素并通过React切换其CSS

[英]Getting HTML element by Id and switch its CSS through React

I have some files that load into my react components, which have HTML code. 我有一些文件加载​​到我的React组件中,这些文件具有HTML代码。 As it is now, the pure HTML code renders just fine, however there is some 'hidden' code that appears whenever you click certain buttons in other parts of the application or on the text above (think of it like panels that expand when you click on it). 现在,纯HTML代码可以很好地呈现,但是,每当您单击应用程序其他部分或上面的文本中的某些按钮时,都会出现一些“隐藏”代码(例如,单击时会展开的面板)在上面)。 The HTML is hidden just using the good old <div id="someId" style="display:none"> . 仅使用良好的<div id="someId" style="display:none">隐藏HTML。

Anyway I am trying to get the correct panel to expand upon clicking their respective buttons. 无论如何,我试图在单击相应的按钮时获得正确的面板以进行扩展。

So in theory, what I need to do is find the element by id, and switch it's display to block whenever needed, and then switch it back when the parent is clicked again. 因此,从理论上讲,我需要做的是按id查找元素,并在需要时将其显示切换为“阻止”,然后在再次单击父级时将其切换回。

Unfortunately I have no idea how to do this and so far have gotten nowhere. 不幸的是,我不知道如何执行此操作,到目前为止却一无所获。 As it is now, I have access to the component's ids. 现在,我可以访问组件的ID。 What I want to know is how in the world can I access that and get to change whatever is rendering? 我想知道的是,在世界上我该如何访问并更改所呈现的内容?

Create your function: 创建您的函数:

function element_do(my_element, what_to_do) {
 document.getElementById(my_element).style.display = what_to_do;
}

and latter in code you can append wherever you want through javascript onclick or not depends what do you need: 后者在代码中,您可以通过javascript onclick附加到所需的位置,这取决于您需要什么:

element_do("someId", "none"); // to hide
element_do("someId", "block"); // to show

or create yourself toggle: 或创建自己的切换:

function toggle_element(element_id) {
      var element = document.getElementById(element_id);
      element.style.display = (element.style.display != 'none' ? 'none' : 'block' );
}
// and you can just call it
<button onClick="toggle_element('some_id')">toggle some element</button>

The react way to do it would be with states. 这样做的反应方式是使用状态。 Assuming that you know how to use states I'd do something like this: 假设您知道如何使用状态,我将执行以下操作:

class ShowHide extends React.Component {
  constructor() {
     super();
      this.state = {myState: true};
      this.onClick = this.onClick.bind(this)
  }

  onClick() {
   this.setState({myState: !this.state.myState})  //set the opposite of true/false
  }

  render() {
    const style = {myState ? "display: none" : "display:block"} //if myState is true/false it will set the style
    return (<div>
     <button onClick={this.onClick}>Click me to hide/show me </button>
     <div id="myDiv" style={style}> Here you will hide/show div on click </div>
    </div>)
  }
}

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

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