无法在 class 组件内部调用 React 挂钩

React hook unable to be called inside of class component

只是想知道我该如何解决这个问题?我听说过使用 consumers 但我不认为这会解决问题,因为我需要在 handleChange() 函数中调用 setSaveEnabled,如果我要做一个。还有哪些我可以走的路?

我在 switch 组件的 onchange 参数中调用了 handleChange()

import SaveContext from "../../context/SaveContext";
class EnableSwitch extends Component {
  constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(checked) {
    this.setState({ checked });
    const { setSaveEnabled } = useContext(SaveContext);
    setSaveEnabled(false);
  }

  render() {
    return (
      <div>
        <Switch
          checked={this.state.checked}
          onChange={() => {
            this.handleChange();
          }}
        />
      </div>
    );
  }
}
React Hook "useContext" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

React hooks 仅在 React 函数组件中有效。

您可以将此 class 组件转换为函数组件:

import SaveContext from "../../context/SaveContext";

const EnableSwitch = () => {
  const { setSaveEnabled } = useContext(SaveContext);  
  const [checked, setChecked] = React.useState(false);

  const handleChange = checked => {
    setChecked(checked);
    setSaveEnabled(false);
  }

  return (
    <div>
      <Switch
        checked={checked}
        onChange={this.handleChange}
      />
    </div>
  );
}

或者如果转换不可接受或繁琐(道具太多,组件太多class等...)那么您可以创建一个高阶组件来访问 React 上下文并注入 setSaveEnabled 函数作为 prop:

const withSaveContext = Component => props => {
  const { setSaveEnabled } = useContext(SaveContext);
  return <Component {...props} setSaveEnabled={setSaveEnabled} />;
}

...

import SaveContext from "../../context/SaveContext";

class EnableSwitch extends Component {
  constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(checked) {
    this.setState({ checked });
    this.props.setSaveEnabled(false);
  }

  render() {
    return (
      <div>
        <Switch
          checked={this.state.checked}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}