【问题标题】:How to Extract the id from a class div in react JS such that i can assign the value of div id to a variable in my code如何从 React JS 中的类 div 中提取 id,以便我可以将 div id 的值分配给我的代码中的变量
【发布时间】:2019-11-05 10:51:13
【问题描述】:

我正在处理 React JS,我想显示我们所在的 div 的名称。例如,在下面的代码中,我希望程序显示在页面上“Hello Pooja We are in div message-box”我已经编写了以下代码,但它似乎不起作用。

import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
  render ()  {
    return (
      <div id='message-box'>
         Hello {this.props.name} We are in div {this.currentTarget.id}
      </div>
    )
  }
}

【问题讨论】:

  • 你需要为div绑定一个event,然后你才能得到id。另一种方法是用id 分配一个variable,然后在这两个地方渲染。
  • 你能解释一下我们如何为 div 绑定事件

标签: reactjs


【解决方案1】:

我不知道你是否想要这样的结果,但你可以通过 Refs 实现它。

function Hello() {
 const [parentDiv, setParentDiv] = useState();
 const ref = useRef();

 useEffect(() => {
   setParentDiv(ref.current.id);
 });

  return (
     <div id='message-box' ref={ref}>
        Hello! We are in div {parentDiv}
     </div>
  )

}

类组件

class Hello extends React.Component {
 state = {
   parentDiv: ""
  };

  ref = React.createRef();

  componentDidMount() {
   this.setState({
     parentDiv: this.ref.current.id
   });
  }

  render() {
     return (
       <div id="message-box" ref={this.ref}>
          Hello! We are in div {this.state.parentDiv}
        </div>
    );
  }
 }

【讨论】:

  • 感谢您的建议,但我想使用类组件而不是功能组件来实现解决方案
  • 我添加了类组件解决方案。 :)
  • 如果我们在代码中添加超过 2 个 div 并且它们都有不同的 id,这段代码是否也会运行
【解决方案2】:

如果您像 &lt;div id='message-box'&gt; 这样声明 div,您已经知道 id。我不确定你为什么需要这个逻辑。

正如@mstoJS 所述,您可以使用refsref 变量用于 dom 元素仅在组件安装到 dom 后设置

这里的技巧是强制第二次渲染显示 ref 的值。

你可以运行下面的sn-p来查看结果。

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.forceUpdate();
  }

  render() {
    console.log("Rendering");
    return <div id = "message-box"
    ref = {
        this.myRef
      } >
      Hello {
        this.props.name
      }&nbsp;
    We are in div {
        this.myRef.current ? this.myRef.current.id : ""
      } <
      /div>
  }
}

ReactDOM.render( < Hello name = "Pooja" / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

为什么我使用this.myRef.current ? this.myRef.current.id : ""

这是因为 refdom 元素仅在组件安装到 dom 之后分配(假设显示在浏览器上),而 render 发生在组件安装到 dom 之前。

你可以运行下面的sn-p,通过console.log语句观察componentWillMountrendercomponentDidMount的顺序。

您应该能够看到 ref 是在 render 方法之后初始化的(它在 componentDidMount 中可用,在 render 之后运行)。

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    console.log("3. Component is mounted on dom. Value of myRef is ", this.myRef.current);
    //this.forceUpdate();
  }

  componentWillMount(){
    console.log("1. Component is about to mount on dom. Value of myRef is ", this.myRef.current);
  }

  render() {
    console.log(
      "2. Component is rendering. Value of myRef is ",
      this.myRef.current
    );
    return (
      <div id="message-box" ref={this.myRef}>
        Hello {this.props.name}
      </div>
    );
  }
}

ReactDOM.render(<Hello />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

this.myRef.current ? this.myRef.current.id : "" 确保我在第一次渲染时没有访问空对象的属性(这显然会引发错误),但可用于第二次渲染(我在 @987654342 中强制通过 this.forceUpdate() @)。

【讨论】:

  • 你能解释一下你为什么使用 { this.myRef.current 吗? this.myRef.current.id : "" } 而不仅仅是 {this.myRef.current.id}
  • 我正在使用它打开具有特定 id 的手风琴(url 包含特定 id 和与手风琴 id 匹配的 id 打开)并且您建议的方法使网页进入无限循环.
  • 我猜 COmponentDidMount 正在使渲染方法被一次又一次地调用
  • componentDidMount 只会运行一次,除非它从 dom 中卸载。如果允许,您可以使用可重现的代码发布新问题或编辑问题。
【解决方案3】:
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
hello(id)
{
 return (
      <div >
         Hello {this.props.name} We are in div {id}
      </div>
    )
}
  render ()  {
    return (
      this.hello({id:message-box})
    ) 
  }
}

【讨论】:

  • 感谢您的建议但我想知道如何使用渲染函数内部的 div 的 id。你建议的方式是我在渲染函数之外创建一个 div ,这违背了问题的目的。
【解决方案4】:

你可以试试这样的。

import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component {
  componentDidMount() {
    const node = ReactDOM.findDOMNode(this);
    console.log(node.id);
  }

  render ()  {
    return (
      <div id='message-box'>
         Hello {this.props.name} We are in div {this.currentTarget.id}
      </div>
    )
  }
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多