reactjs - 在ajax调用后反应更新dom模板
问题描述
我正在使用 Laravel + React,目前 DOM 中有标记。
我有一个刀片容器:<span class="preview-button"
React 呈现一个按钮。
单击此按钮时,会打开一个模式,我想在其中更改其某些值。
但是我收到一个错误Uncaught ReferenceError: plpModalImg1 is not defined
如何在 ajax 调用后更新现有的模式模板?
<div class='row'>
<div id="productcontainer" class="col-12">
<ul class='row'>
@foreach($arr as $item)
<li class='col-6'>
<div class="inner">
<span class="preview-button" data-title="{{ $item['title'] }}"></span>
</div>
</li>
@endforeach
</ul>
</div>
<div class="modal fade" id="modal-product-container" tabindex="-1" role="dialog" aria-labelledby="modal-product" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-product">Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
// NEED TO UPDATE VALUES HERE
<img id="modal-img1" src="{imgTitle}" alt="">
</div>
</div>
</div>
</div>
@stop
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class PreviewBtn extends React.Component {
constructor() {
super();
this.state = { containerData: "" };
}
componentDidMount() {
this.setState({
containerData: ReactDOM.findDOMNode(this).parentNode.getAttribute("data-title"),
plpModalImg1: document.getElementById("modal-img1"),
});
}
_handleClick(v1){
var url = '/api/item/' + v1;
axios
.post(url)
// NEED TO UPDATE VALUES HERE
.then(response => this.setState({ajaxData: response.data},
()=> plpModalImg1.setState({
imgTitle: response.data.itemName
})
)
)
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<button onClick={(e) => this._handleClick(this.state.containerData)} type="button" className="btn btn-primary" data-toggle="modal" data-target="#modal-product-container">Preview</button>
);
}
}
Array.prototype.forEach.call(
document.getElementsByClassName('preview-button'),
function(el) {
ReactDOM.render(<PreviewBtn />, el)
}
)
解决方案
plpModalImg1
由您在该州定义。这意味着您必须通过 this.state.plpModalImg1 访问它
更新的答案
因此修改您的部分类似于以下内容:
this.state.plpModalImg1.setAttribute('src', response.data.fabricName)
推荐阅读
- python - ASCII 字符的 QValidator 保持无效
- c# - 如何将嵌套对象添加到 DataGrid C# WPF
- php - 在 laravel 应用程序中托管 laravel 应用程序
- c# - 为什么我的本地 DateTime 没有转换为 UTC?
- php - 在一个 MySQL 列中存储和检索数组值
- python - 运行以下代码时出现错误(找到带有暗淡 3 的数组。预计估计器 <= 2)
- powershell - PowerShell中的“导出-csv”
- c# - 如何将 C# 中的嵌套字典结构复制到 Lua
- sql - 如何在具有数组参数的 exec Oracle 过程中传递参数
- excel - 如何正确实现自定义查找功能 VBA Excel?