我正在尝试创建一个包含多个字段的表单,这些字段之一是包含以下内容的容器:
<form id="formAddEvent" className="w3-container w3-cell" autoComplete="off" action="#" onSubmit={this.submitHandler}>
<div id="photoContainer" className="w3-container w3-cell w3-padding-16">
<img id ="uploadedPhoto" className="uploadedPhoto" alt=""/>
<img src={photo} id="logoPhoto" className="logoPhoto" alt=""/>
<h6 id="loadPhotoText" className="loadPhotoText w3-center">Carica una foto</h6>
<input type="file" className="inputPhoto" id="inputPhoto" name="photo" accept="image/*" onChange={this.imageSelectedHandler} />
</div>
</form>
方法imageSelectHandler
执行此操作:
imageSelectedHandler = (event) =>{
event.preventDefault();
document.getElementById("uploadedPhoto").src=path+event.target.files[0].name;
document.getElementById("logoPhoto").style.display="none";
document.getElementById("loadPhotoText").style.display="none";
}
提交方法是:
submitHandler = (event) =>{
event.preventDefault();
}
我的问题是,有时,当我更改图像时,当前页面会重新加载。 如何避免这种行为? 预先谢谢你。
这是完整的代码:
import React, {Component} from "react";
import { withAlert } from "react-alert";
import Period from "./Period";
import { Provider } from "react-alert";
import AlertTemplate from "react-alert-template-basic";
import axios from "axios";
import ConfirmUpdate from "./ConfirmUpdate";
import ConfirmAddEvent from "./ConfirmAddEvent";
import ConfirmDraft from "./ConfirmDraft";
import Topic from "./Topic";
import close from "./../../image/close.png";
import photo from "./../../image/photo.png";
import add from "./../../image/plus.png";
import "./../../stylesheet/AddEventForm.css";
var path = "/eventImage/";
class AddEventForm extends Component{
constructor(props){
super(props);
this.state={
topics: [],
addPeriodIsClicked: false,
periodsList: [],
showConfirmUpdate: false,
showConfirmAddEvent: false,
showConfirmDraft: false
}
this.removeTopicFromArray = this.removeTopicFromArray.bind(this);
this.updateAddPeriodIsClicked = this.updateAddPeriodIsClicked.bind(this);
this.appendResult=this.appendResult.bind(this);
this.updateEventHandler = this.updateEventHandler.bind(this);
this.addEventHandler = this.addEventHandler.bind(this);
this.draftEventHandler = this.draftEventHandler.bind(this);
}
submitHandler = (event) =>{
event.prevetDefault();
event.stopPropagation();
return false;
}
onCloseHandler = () =>{
this.props.updateAddEventIsClicked();
}
imageSelectedHandler = (event) =>{
event.preventDefault();
event.stopPropagation();
document.getElementById("uploadedPhoto").src=path+event.target.files[0].name;
document.getElementById("logoPhoto").style.display="none";
document.getElementById("loadPhotoText").style.display="none";
return false;
}
removeTopicFromArray = (topic) =>{
var array = [...this.state.topics];
var index = -1;
for(let i=0; i<array.length; i++){
if(topic.props.topicName === array[i]){
index = i;
break;
}
}
array.splice(index,1);
this.setState({
topics: array
});
}
addTopicContainerHandler = () =>{
var arrJSON = localStorage.getItem("arr");
var arr = JSON.parse(arrJSON);
var topicName = (document.getElementById("inputTopic")).value;
var firstInstanceInLocalStorage = true;
var firstInstance = true;
for(let i=0; i<arr.length; i++){ //verifico se esiste una copia del topicName tra quelle già memorizzate, in caso contrario la memorizzo
if(topicName.toUpperCase() === arr[i].toUpperCase()){
firstInstanceInLocalStorage = false;
}
}
if(firstInstanceInLocalStorage){
arr.push(topicName);
var objectJSON = JSON.stringify(arr);
localStorage.setItem("arr",objectJSON);
}
for(let i=0; i<this.state.topics.length; i++){ //verifico se esiste una copia del topicName tra quelle già inserite, in caso contrario la inserisco
firstInstance = true;
if(this.state.topics[i].toUpperCase() === topicName.toUpperCase()){
firstInstance = false;
break;
}
}
if(firstInstance){
this.setState({
topics: [...this.state.topics, topicName]
});
axios.post("http://localhost:8080/topicEvents",topicName).then(topicEvents=>{
console.log(topicEvents.data)
})
}
(document.getElementById("inputTopic")).value = "";
}
updateAddPeriodIsClicked = () =>{
this.setState({
addPeriodIsClicked: !this.state.addPeriodIsClicked
});
}
appendResult = (periods) =>{
this.setState({
periodsList: []
});
console.log(periods)
var periodsList= [];
for(let i=0; i< periods.length; i++){
periodsList.push(periods[i]);
}
this.setState({
periodsList: periodsList
});
var length = periodsList.length/4;
var div;
var att;
var period;
var dateListContainer = document.getElementById("dateListContainer");
while(dateListContainer.childElementCount !== 0){
dateListContainer.removeChild(dateListContainer.firstChild);
}
for(let i=0; i<length; i++){
period = "Dal "+ (periodsList[0 + (i*4)]) + " Al "+ (periodsList[1 + (i*4)]) + " - Dalle ore "+ (periodsList[2 + (i*4)]) + " Alle ore "+ (periodsList[3 + (i*4)]);
div = document.createElement("DIV");
att = document.createAttribute("class");
att.value="w3-container";
div.setAttributeNode(att);
div.innerHTML = "<h6>"+period+"</h6>";
dateListContainer.appendChild(div);
}
if(this.state.addPeriodIsClicked){
this.updateAddPeriodIsClicked();
}
}
buttonHandler = (event) =>{
var inputPhoto = document.getElementById("uploadedPhoto").src;
var eventName = document.getElementById("eventName").value;
var periodLength = this.state.periodsList.length;
var detailsBox = document.getElementById("detailsBox").value;
var topicsLength = this.state.topics.length;
if((inputPhoto!=="")&&(eventName!=="")&&(periodLength!==0)&&(detailsBox!=="")&&(topicsLength!==0)){
if(this.props.eventInfoIndex!==-1){
if(event.target.getAttribute("id")==="update"){
this.updateConfirmUpdate();
} else {
this.props.updateAddEventIsClicked();
}
} else {
if(event.target.getAttribute("id")==="draft"){
this.updateConfirmDraft();
} else {
this.updateConfirmAddEvent();
}
}
} else {
this.props.alert.error("Campi incompleti");
}
}
addEventHandler(){
var inputPhoto = document.getElementById("uploadedPhoto").src;
var eventName = document.getElementById("eventName").value;
var detailsBox = document.getElementById("detailsBox").value;
var array = localStorage.getItem("eventsArray");
var eventsArray = JSON.parse(array);
var isDraft = false;
var id = eventsArray[eventsArray.length-1].id+1;
var newEvent = {
id: id,
name: eventName,
photo: inputPhoto,
periods: this.state.periodsList,
description: detailsBox,
topic: this.state.topics,
isDraft: isDraft,
isMapped: false
}
axios.post("http://localhost:8080/events",newEvent).then(events=>{
console.log(events.data)
})
eventsArray.push(newEvent);
localStorage.setItem("eventsArray",JSON.stringify(eventsArray));
this.props.updateSomethingIsChange();
this.props.updateAddEventIsClicked();
}
draftEventHandler(){
var inputPhoto = document.getElementById("uploadedPhoto").src;
var eventName = document.getElementById("eventName").value;
var detailsBox = document.getElementById("detailsBox").value;
var array = localStorage.getItem("eventsArray");
var eventsArray = JSON.parse(array);
var isDraft = true;
var id = eventsArray[eventsArray.length-1].id+1;
var newEvent = {
id: id,
name: eventName,
photo: inputPhoto,
periods: this.state.periodsList,
description: detailsBox,
topic: this.state.topics,
isDraft: isDraft,
isMapped: false
}
axios.post("http://localhost:8080/events",newEvent).then(events=>{
console.log(events.data)
})
eventsArray.push(newEvent);
localStorage.setItem("eventsArray",JSON.stringify(eventsArray));
this.props.updateSomethingIsChange();
this.props.updateAddEventIsClicked();
}
updateEventHandler(){
var inputPhoto = document.getElementById("uploadedPhoto").src;
var eventName = document.getElementById("eventName").value;
var detailsBox = document.getElementById("detailsBox").value;
var array = localStorage.getItem("eventsArray");
var eventsArray = JSON.parse(array);
eventsArray[this.props.eventInfoIndex].photo = inputPhoto;
eventsArray[this.props.eventInfoIndex].name = eventName;
eventsArray[this.props.eventInfoIndex].periods = this.state.periodsList;
eventsArray[this.props.eventInfoIndex].description = detailsBox;
eventsArray[this.props.eventInfoIndex].topic = this.state.topics;
var update = {
name: eventName,
photo: inputPhoto,
periods: this.state.periodsList,
description: detailsBox,
topic: this.state.topics,
isDraft: eventsArray[this.props.eventInfoIndex].isDraft,
isMapped: eventsArray[this.props.eventInfoIndex].isMapped
}
axios.put("http://localhost:8080/events/"+eventsArray[this.props.eventInfoIndex].id,update).then(events=>{
console.log(events.data)
})
localStorage.setItem("eventsArray",JSON.stringify(eventsArray));
this.props.updateSomethingIsChange();
this.props.updateAddEventIsClicked();
}
updateConfirmAddEvent = () =>{
this.setState({
showConfirmAddEvent: !this.state.showConfirmAddEvent
})
}
updateConfirmDraft = () =>{
this.setState({
showConfirmDraft: !this.state.showConfirmDraft
})
}
updateConfirmUpdate = () =>{
this.setState({
showConfirmUpdate: !this.state.showConfirmUpdate
})
}
autoComplete = () => {
var arrJSON = localStorage.getItem("arr");
var arr = JSON.parse(arrJSON);
var inp = document.getElementById("inputTopic");
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
closeAllLists();
if (!val) {
return false;
}
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items w3-container");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, val.length).toUpperCase() === val.toUpperCase()) {
b = document.createElement("DIV");
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
});
function closeAllLists(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt !== x[i] && elmnt !== inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
componentDidMount(){
var events = localStorage.getItem("eventsArray");
var eventsArray = JSON.parse(events);
var index = this.props.eventInfoIndex;
if(index !== -1){ //vuol dire che addEventForm è stato chiamato da un evento e non dal pulsante del menu
document.getElementById("uploadedPhoto").src=eventsArray[index].photo;
document.getElementById("logoPhoto").style.display="none";
document.getElementById("loadPhotoText").style.display="none";
document.getElementById("eventName").value = eventsArray[index].name;
document.getElementById("detailsBox").value = eventsArray[index].description;
this.setState({
periodsList: eventsArray[index].periods,
topics: eventsArray[index].topic,
});
this.appendResult(eventsArray[index].periods);
}
}
render(){
return(
<div id="addEventWrapper" className="modalAddEvent">
<div id="modal" className="w3-modal">
<div className="w3-modal-content w3-card-4 w3-animate-zoom">
<form id="formAddEvent" className="w3-container w3-cell" autoComplete="off" action="#" onSubmit={this.submitHandler}>
<div id="photoNameEventContainer" className="w3-panel">
<div id="infoTitleContainer" className="w3-container">
<h2 id="infoTitle">Informazioni di base</h2>
</div>
<div id="photoEventContainer" className="w3-panel w3-cell-row">
<div id="labelPhotoContainer" className="w3-container w3-cell w3-left-align">
<h6 id="labelPhoto">Foto dell'evento</h6>
</div>
<div id="photoContainer" className="w3-container w3-cell w3-padding-16">
<img id ="uploadedPhoto" className="uploadedPhoto" alt=""/>
<img src={photo} alt="" id="logoPhoto" className="logoPhoto" />
<h6 id="loadPhotoText" className="loadPhotoText w3-center">Carica una foto</h6>
<input type="file" className="inputPhoto" id="inputPhoto" name="photo" accept="image/*" onChange={this.imageSelectedHandler} />
</div>
</div>
<div id="nameEventContainer" className="w3-panel w3-cell-row">
<div id="labelNameContainer" className="w3-container w3-cell w3-left-align">
<h6 id="labelName">Nome dell'evento</h6>
</div>
<div id="inputNameContainer" className="w3-container w3-cell w3-padding-16">
<input type="text" id="eventName" className="w3-input" name="eventName"/>
</div>
</div>
</div>
<div id="dateContainer" className="w3-panel">
<button onClick={this.updateAddPeriodIsClicked}>Scegli una o più date</button>
</div>
<div id="dateListContainer" className="w3-panel"/>
<div id="detailsContainer" className="w3-panel">
<div id="detailsTitleContainer" className="w3-container">
<h2 id="detailsTitle">Dettagli</h2>
</div>
<div id="descriptionContainer" className="w3-container w3-cell-row">
<div id="labelDescriptionContainer" className="w3-container w3-cell w3-left-align">
<h6 id="labelDescription">Aggiungi una descrizione</h6>
</div>
<div id="boxDescriptionContainer" className="w3-container w3-cell">
<textarea id="detailsBox" name="description"/>
</div>
</div>
</div>
<div id="topicContainer" className="w3-panel w3-cell-row">
<div id="labelTopicContainer" className="w3-container w3-cell w3-left-align">
<h6 id="labelTopic">Aggiungi un Topic</h6>
</div>
<div id="inputTopicContainer" className="w3-container w3-cell">
<input type="text" id="inputTopic" className="w3-input" name="inputTopic" onInput={this.autoComplete}/>
</div>
<div id="addBtnContainer" className="w3-container w3-cell">
<img src={add} alt="+" className="addBtn" onClick={this.addTopicContainerHandler}/>
</div>
</div>
<div id="topicListContainer" className="w3-panel">
{this.state.topics.map(topic =>(
<Topic key={topic} id={topic} topicName={topic} removeTopicFromArray={this.removeTopicFromArray}/>
))}
</div>
{ (this.props.eventInfoIndex===-1) &&
<div id="buttonContainer" className="w3-panel w3-cell-row">
<div id="draftContainer" className="w3-container w3-cell">
<button id="draft" onClick={this.buttonHandler}>Salva come bozza</button>
</div>
<div id="publishContainer" className="w3-container w3-cell">
<button id="publish" onClick={this.buttonHandler}>Pubblica</button>
</div>
</div>
}
{ (this.props.eventInfoIndex!==-1) &&
<div id="buttonContainer" className="w3-panel w3-cell-row">
<div id="draftContainer" className="w3-container w3-cell">
<button id="undo" onClick={this.buttonHandler}>Annulla</button>
</div>
<div id="publishContainer" className="w3-container w3-cell">
<button id="update" onClick={this.buttonHandler}>Apporta le modifiche</button>
</div>
</div>
}
</form>
<div className="closeBtnContainer w3-cell">
<img src={close} alt="x" onClick={this.onCloseHandler} className="cancelBtn"/>
</div>
</div>
</div>
<div id="periodContainer">
{ this.state.addPeriodIsClicked &&
<Provider template={AlertTemplate} {...{position: "bottom center", offset: "100px", transition: "scale", timeout: 5000}}>
<Period updateAddPeriodIsClicked={this.updateAddPeriodIsClicked} appendResult={this.appendResult} periodsList={this.state.periodsList}/>
</Provider>
}
</div>
{this.state.showConfirmUpdate &&
<ConfirmUpdate
updateConfirmUpdate={this.updateConfirmUpdate}
updateEventHandler={this.updateEventHandler}
eventName={this.props.eventName}/>}
{this.state.showConfirmAddEvent &&
<ConfirmAddEvent
updateConfirmAddEvent={this.updateConfirmAddEvent}
addEventHandler={this.addEventHandler}/>}
{this.state.showConfirmDraft &&
<ConfirmDraft
updateConfirmDraft={this.updateConfirmDraft}
draftEventHandler={this.draftEventHandler}/>}
</div>
);
}
}
export default withAlert(AddEventForm);
答案 0 :(得分:0)
我想您需要从自己的SubmitHandler函数中return false;
和event.stopPropagation();
来防止Submit事件的进一步传播。
submitHandler = (event) => {
event.preventDefault();
event.stopPropagation();
return false;
}