【问题标题】:Getting React unique ID in didMount在 didMount 中获取 React 唯一 ID
【发布时间】:2026-02-17 18:55:02
【问题描述】:

我有一个自定义反应输入组件。我希望我的所有输入在它们旁边都有一个小提示(一个星号),悬停时会显示一个提示。问题是我无法将弹出点初始化到这个确切的星号,所以它显示了这个特定组件的消息。现在它只是将消息替换为最后安装的组件的消息。

我的问题是 - 我将如何引用确切的元素。我可以从 didMount 获取 React ID 吗?我可以使用渲染指向它吗,例如 $(this.render() + 'i') -> (理想情况)。

import React, { Component, PropTypes } from 'react'

export default class Input extends Component {

  componentDidMount() {
    var html = this.props.popup;
    console.log(this);
    $('.inverted.asterisk.icon').popup({
      html: html,
      variation: 'inverted'
    });
  }

  render() {
    return (
      <div className="ui icon fluid input">
       <input
              type={this.props.type}
              value={this.props.value}
              onChange={this.props.onChange}
              name={this.props.name}
       />
       <i className="inverted disabled asterisk link icon" />
      </div>
    )
  }
}

Input.propTypes = {
  type: PropTypes.string,
  name: PropTypes.string,
  popup: PropTypes.string,
  value: PropTypes.node,
  onChange: PropTypes.func
}

【问题讨论】:

    标签: input reactjs components semantic-ui


    【解决方案1】:

    您可以将ref 属性分配给渲染函数中的任何元素以获取对其的引用。

    分配参考

    <i ref="icon" className="inverted disabled asterisk link icon" />
    

    在componentDidMount中使用

      componentDidMount() {
        var html = this.props.popup;
        console.log(this);
        $(this.refs.icon).popup({
          html: html,
          variation: 'inverted'
        });
      }
    

    jsfiddle example

    【讨论】:

    • 太棒了!谢谢!