我有一个名为Settings
的组件,其中包含一个变量(IsActive),useState默认为true。我需要通过单击按钮从该组件外部更新变量的状态(IsActive)。该按钮不是该组件的一部分。如何通过单击按钮来更改该变量的状态。
文件Settings.tsx
import React, { useState } from "react";
import ReactDOM from "react-dom";
export const reportSettings = () => {
ReactDOM.render(<Settings />, document.querySelector('.setting-container'));
};
const Settings = () => {
const [isActive, setIsActive] = useState(true);
return (
<div>
<input type="text" disabled={isActive} />
</div>
);
};
export default Settings;
我有另一个名为index.tsx的文件,其中有一个按钮,单击它我需要更改设置组件的状态。我该怎么做?
文件 Index.tsx
$(".btn-success").on("click", function() {
//change state of settings component
});
最佳答案
如果您只使用 React,我建议您使用 Redux 或 React 自定义 Hook 。由于 JQuery 也被使用,还有另一种方法 - 通过自定义事件
const event = new CustomEvent("settings", {
isActive: false
});
$(".btn-success").on("click", function() {
window.dispatchEvent(event);
});
// Settings.tsx
const [isActive, setIsActive] = useState(true);
React.useEffect(() => {
const toggleFunc = (ev) => {
setIsActive(ev.isActive)
};
window.addEventListener("settings", toggleFunc);
// Remove listener
return () => window.removeEventListener("settings", toggleFunc);
});
关于javascript - 在 React 中从该组件外部更新该功能组件的状态(单击另一个文件中的按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60752536/