在 React 中从该组件外部(单击另一个文件中的按钮)更新功能组件的状态

Update state of a functional component from outside of that component(on click of button in another file) in React

我有一个名为 Settings 的组件,其中包含一个 useState 默认为 true 的变量 (IsActive)。我需要通过单击按钮从该组件外部更新变量 (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
  });

您可以使用 CustomEvents。创建自定义事件。从 jquery 触发事件,并在您的 React 组件上触发事件监听器。调用事件侦听器时更新状态。

如果您只使用 React,我会建议您使用 Redux 或 React 自定义挂钩。由于 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);
  });

您可以将 isActive 提升到上层组件,使其可供按钮更改。因此,将 isActive 变量提升到 index.tsx 并将其传递给按钮和设置组件。