首页 > 解决方案 > ReactJS 如何正确调用多个函数

问题描述

我想解释一下我今天遇到的问题。

目前,我有 2 个可以正常工作的功能

我希望我可以在一个按钮上同时拥有这两种功能

当它们分开时,功能正常工作,我的问题,当我尝试在单个按钮上传递它们时,出现错误“无法读取未定义的属性'preventDefault'”

我该如何解决这个问题?谢谢大家

为代码腾出空间

我的第一个功能

putBack = (e, id) => {
e.preventDefault();
const config = {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ id: id, livree: new Date().toISOString().slice(11, 16)}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true })); }

我的第二个功能

onChange = (id, status) => {
const validatedorder = JSON.parse(localStorage.getItem("validated-order") || "{}");
localStorage.setItem("validated-order", JSON.stringify({ ...validatedorder, [id]: status }))

this.setState({ color: 'red' });
this.setState({ title: 'Confirmer la livraison' });

console.log('cliqué pour preparation')
this.setState({
  statut :'preparation',
  id,
});
}

我的多种功能

megaTryMulti(e){
e.preventDefault();
this.putBack();
this.onChange();
}

功能分开。(那个工作)

<form onSubmit={(e) => this.putBack(e, datass.id)}>
   <button type="submit">PUT</button>
</form>

第二个功能分开(有效)

<Button style={{ backgroundColor: status === undefined || status === false ? "red" : "#4DD5C7" }} disabled={status === false} onClick={() => this.onChange(datass.id, !status)} className="buttonForLancerMaybe">{status === undefined ? "Lancer" : status === true ? "Confirmer la livraison" : "SERVI"}</Button>

多功能(这是我的问题,她不工作)

  <form onSubmit={(e) => this.megaTryMulti(e)}>  
     <Button type="submit">test</Button>
   </form>

标签: javascriptreactjsfunction

解决方案


您需要将所有希望收到的参数传递给putBack,以进行传递。采用 onSubmit 事件和 id 的形式,并采用相同的 id 和状态onChangemegaTryMultiputBackonChange

megaTryMulti(e, datass, status){
  e.preventDefault();
  this.putBack(e, datass.id);
  this.onChange(datass.id, !status);
}

用法:

<form onSubmit={(e) => this.megaTryMulti(e, datass, status)}>  
  <Button type="submit">test</Button>
</form>

推荐阅读