首页 > 解决方案 > 在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">&times;</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)
  }
)

标签: reactjs

解决方案


plpModalImg1由您在该州定义。这意味着您必须通过 this.state.plpModalImg1 访问它

更新的答案

因此修改您的部分类似于以下内容:

this.state.plpModalImg1.setAttribute('src', response.data.fabricName)

推荐阅读