【问题标题】:In React, Is it good practice to search for certain element in DOM?在 React 中,在 DOM 中搜索特定元素是一种好习惯吗?
【发布时间】:2018-03-11 20:04:09
【问题描述】:

只为元素指定 className 这样我以后可以通过 getElementsByClassName 在 DOM 中找到它进行操作是否很好?

【问题讨论】:

    标签: reactjs dom classname


    【解决方案1】:

    添加一个类来查找 DOM 元素?当然可以,但refs 可能是更好的解决方案。

    操作 DOM 元素?那是绝对不行的。由 React 管理的 DOM 部分除了 React 本身之外,不应该被其他任何东西操作。

    【讨论】:

    • 任何通过 React 创建的元素都不应手动操作。其他都可以。
    【解决方案2】:

    如果你有 jQuery 或者类似的背景,你会倾向于像这样直接操作元素:

    <div class="notification">You have an error</div>
    
    .notification {
       display: none;
       color: red;
    }
    
    .show {
       display: block;
    }
    
    handleButtonClick(e) {
       $('.notification').addClass('show');
    }
    

    在 React 中,您可以通过声明您的元素(组件)在应用程序的不同状态下应该做什么来实现这一点。

    const Notification = ({ error }) => {
       return error
          ? <div className="notification">You have an error</div>
          : null;
    }
    
    class Parent extends React.Component {
       state = { error: false };
    
       render() {
          return (
             <div>
                <Notification error={this.state.error} />
                <button onClick={() => this.setState({ error: true })}>
                   Click Me
                </button>
       }
    }
    

    上面的代码未经测试,但应该给你一个大致的想法。

    默认情况下,Parenterror的状态为false。在那种状态下,Notification 不会渲染任何东西。如果单击该按钮,error 将是true。在该状态下,Notification 将呈现 div

    尝试以声明式而非命令式的方式思考。

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      在使用 React 时,您应该考虑如何使用状态来控制组件的呈现方式。 this.setState 执行重新渲染,这意味着您可以通过更改 this.state 来控制元素的渲染方式。这是一个小例子。我使用 this.state.show 作为布尔值来更改 HTML 元素的不透明度。

      constructor(props) {
        super(props)
        this.state = {
          show: true
        }
      }
      
      handleClick() {
        this.setState({show: false})
      }
      
      render() {
        const visibility = this.state.show ? 1 : 0
        return (
          <button style={{opacity: visibility} onClick={() => this.handleClick()}>
             Click to make this button invisible
          </button>
        )
      }
      

      【讨论】:

      • 是的,但是如果我想,react 会派上用场,例如,通过单击另一个 React 组件来隐藏菜单(包含 react 组件),或者在调整窗口大小时管理 React 组件?
      • 取决于你所说的窗口调整大小,但对于第一个,是的。您可以使用相同的逻辑来删除和添加 DOM 元素,例如:{this.state.show ? &lt;Component/&gt; : null }&lt;Component/&gt; 不会被挂载,直到 this.state.show 更改为 true,就像我的不透明度示例一样。
      猜你喜欢
      • 2020-05-09
      • 2022-01-03
      • 2016-07-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 2016-03-21
      相关资源
      最近更新 更多