gpt4 book ai didi

javascript - 在 main 函数中传递多个函数

转载 作者:行者123 更新时间:2023-12-01 00:57:01 25 4
gpt4 key购买 nike

我正在尝试实现一种解决方法,根据 if 条件调用主函数内的两个函数。主要功能是切换onClick/onChange事件处理程序。

fetchData = command => e => {
if (e.target.tagName === "BUTTON") {
console.log("Button Clicked!");

this.setState({
command
});

this.ButtonData = command => {
console.log(command, "command received");
};
} else if (e.target.tagName === "INPUT") {
console.log("Input Clicked!");

this.setState({
command
});

this.InputData = command => {
console.log(command, "command received");
};
}
};

该代码仅在第一次控制台打印“单击”之前有效,但随后不会在 if 条件中调用的函数内执行。

这是工作沙箱:https://codesandbox.io/embed/pensive-bash-fmmmd

请帮助实现同样的目标。

最佳答案

这是正确的方法,请尝试将其粘贴到您的示例中:

import React, { Component } from "react";

export default class extends Component {
constructor() {
super();

this.state = {
command: "",
text_start: "enter text one",
text_end: "enter text two"
};
}

componentDidMount() {
this.fetchData();
}

buttonData = command => {
console.log(command, "command received");
};

inputData = command => {
console.log(command, "command received");
};

fetchData = command => e => {
if (e.target.tagName === "BUTTON") {
console.log("Button Clicked!");

this.setState({
command
});

this.buttonData(command);
} else if (e.target.tagName === "INPUT") {
console.log("Input Clicked!");

this.setState({
command
});

this.inputData(command);
}
};
render() {
return (
<>
<div>
<button value="start" onClick={this.fetchData("start")}>
Start
</button>
<button value="stop" onClick={this.fetchData("stop")}>
Stop
</button>
</div>

<div>
<input
type="text"
name="start"
value={this.state.text_start}
onChange={this.fetchData("e")}
/>

<input
type="text"
name="end"
value={this.state.text_end}
onChange={this.fetchData("e")}
/>
</div>
</>
);
}
}

关于javascript - 在 main 函数中传递多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com