我正在尝试实现以下是/否按钮:
import React, { useState } from "react";
const YesNoComponentFunctional = () => {
const [button, setButton] = useState("");
const onYesPress = () => {
setButton("Yes");
console.log({ button });
};
const onNoPress = () => {
setButton("No");
console.log({ button });
};
return (
<div>
<button onClick={() => onYesPress()}>Yes</button>
<button onClick={() => onNoPress()}>No</button>
</div>
);
};
export default YesNoComponentFunctional;
我从这篇文章中得到了。
而且我不明白为什么我必须单击按钮两次才能正确向控制台显示消息。为什么会这样?
setButton 是异步方法,您的按钮状态不会立即更新。 您可以使用 useEffect 钩子来检查按钮的值是否更新。
useEffect(() => {
console.log({button});
}, [button]);
set函数(本例中为 setButton(是异步的。为了得到确切的结果,你需要使用useEffect。
import React, { useState, useEffect } from "react";
const YesNoComponentFunctional = () => {
const [button, setButton] = useState("");
const onYesPress = () => {
setButton("Yes");
};
const onNoPress = () => {
setButton("No");
};
useEffect(() => {
console.log({button})
}, [button])
return (
<div>
<button onClick={() => onYesPress()}>Yes</button>
<button onClick={() => onNoPress()}>No</button>
</div>
);
};
export default YesNoComponentFunctional;