【问题标题】:document.queryselector returns null and I am unsure whydocument.queryselector 返回 null,我不确定为什么
【发布时间】:2020-11-11 19:37:47
【问题描述】:

这是在 react/js 应用程序的前端。在我的名为供应商容器的文件中,以下是我的组件 Did Mount 功能的一部分:

componentDidMount() {
    var element = document.querySelector('.supplier-data');
}

然后在渲染方法中我调用另一个文件,该文件调用另一个文件,该文件调用另一个文件,该文件在其渲染方法中具有以下内容:

<tbody>
                        {this.props.data.map((dataItem, data_k) => (
                            <tr key={data_k} className={dataItem.deleted_at ? 'deleted-supplier' : null}>
                                {this.props.config.map((configItem, conf_k) => (
                                    <td key={` ${conf_k}-${data_k} `} className="align-middle supplier-data">
                                        {this.getValue(dataItem, configItem)}
                                    </td>
                                ))}
                            </tr>
                        ))}
                    </tbody>

注意 td 标签中的 className = supplier-data。我正在尝试从 getValue 函数访问值,如下所示:

getValue(dataItem, configItem, defaultVal = 'N/A') {

    var value = null;

    if (configItem.content) {
        var value = this._getValueFromMethod(dataItem, configItem);
    }

    if (configItem.attribute && configItem.attribute.search(/\./) !== -1) {
        var value = this._getValueFromSegmentAttribute(dataItem, configItem)
    }

    if (configItem.attribute && configItem.attribute.search(/\./) == -1) {
        var value = this._getValueFromStaticAttribute(dataItem, configItem);
    }

    if (configItem.dateFormat && value) {
        value = moment(value).format(configItem.dateFormat);
    }

    return value || defaultVal;
}

这里的其他功能并不重要。当我从上面的 componentDidMount 控制台日志元素时,我得到空值。我该如何解决?

【问题讨论】:

    标签: reactjs jquery-selectors


    【解决方案1】:

    你应该使用React's ref而不是使用querySelector来获取元素

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2014-09-25
      • 2021-04-16
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      相关资源
      最近更新 更多