javascript - 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>
解决方案
您需要将所有希望收到的参数传递给putBack
,以进行传递。采用 onSubmit 事件和 id 的形式,并采用相同的 id 和状态onChange
megaTryMulti
putBack
onChange
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>
推荐阅读
- python - 使用python函数式编程将csv文件导入sqllite3
- python - 下面的 C 语句是什么意思?((int*) & var)
- python - Pyspark 读取带有模式的 csv、标头检查并存储损坏的记录
- python - 尽管进程已死,为什么我会收到子进程资源警告?
- python - Pandas 中的高级数据透视表
- ios - 如何将我的项目从使用 Storyboard 转变为不再使用 Storyboard?
- javascript - 限制安卓设备的字段输入
- vue.js - 在Vue router-link中使用Object作为参数的路径问题
- windows - 绑定地址失败 http://127.0.0.1:59074: 地址已在使用中
- domain-driven-design - 域模型中的 ID,以防自然 ID 不可用