我很困惑。在刺激控制器中,我发现目标的行为不一致。
通过importmap pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true使用pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
我有一个基本形式的刺激控制器。
<%= form_with model: @message, data: { controller: "message-form" } do |form| %>
<%= form.file_field :attachments, class: 'file-input', id: 'file-input', multiple: true, hidden: "hidden",
data: { message_form_target: "attachmentInput" } %>
<i class="fa-solid fa-paperclip fa-lg" data-action="click->message-form#openAttachments"></i>
<% end %>import {Controller} from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["messageInput", "sendBtn", "attachmentInput"]
connect() {
this.inputIsEmpty()
console.log(this.attachmentInputTarget) // Outputs HTML element
}
openAttachments(){
this.attachmentInputTarget.click()
this.attachmentInputTarget.removeAttribute("hidden")
setInterval(this.hideAttachments, 5000)
}
hideAttachments(){
let attachmentInput = document.querySelector('#file-input')
console.log(this.attachmentInputTarget) // Undefined
console.log(attachmentInput) // Outputs HTML element
console.log(document.getElementById('file-input') == this.attachmentInputTarget) // false
if (!document.getElementById('file-input').files[0]) {
attachmentInput.setAttribute("hidden", "hidden")
} else {
attachmentInput.removeAttribute("hidden")
}
}
}因此,connect()中的attatchmentInputTarget按照我的预期操作,并输出hideAttachments元素,但是当hideAttachments被调用时,attatchmentInputTarget是未定义的。
发布于 2022-11-22 08:35:02
好吧,我把这一切都写出来了。
由于对setInterval的延迟调用,hideAttachments作为普通JS在刺激控制器外部被调用,因此没有对Target的引用。
https://stackoverflow.com/questions/74529613
复制相似问题