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

Getting HTML element by Id and switch its CSS through React

本文关键字:React CSS 获取 Id HTML 元素 通过      更新时间:2023-09-26

我有一些文件加载到我的react组件中,其中包含HTML代码。就像现在一样,纯HTML代码呈现得很好,但是当你点击应用程序其他部分的某些按钮或上面的文本时,就会出现一些"隐藏"代码(把它想象成当你点击它时展开的面板)。HTML是隐藏的,只是使用旧的<div id="someId" style="display:none">

无论如何,我正试图得到正确的面板展开后,点击各自的按钮。

理论上,我需要做的是通过id找到元素,并在需要时将其显示切换为block,然后在再次单击父元素时将其切换回来。

不幸的是,我不知道如何做到这一点,到目前为止还没有得到任何地方。现在,我可以访问组件的id。我想知道的是我怎样才能访问它并改变正在渲染的东西?

创建函数:

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

和后面的代码,你可以追加任何你想通过javascript的onclick或不取决于你需要什么:

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

或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>

最有效的方法是使用状态。假设您知道如何使用状态,我将这样做:

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