React常用通信方式

123 阅读1分钟

通过props和回调函数

const Parent = () => {
  const callback = (msg) => {
    console.info(msg, "msg");
  };
  return (
    <div>
      <Child callback={callback} message="传递给子组件的信息" />
    </div>
  );
};

export default Parent;

const Child = (props) => {
  const cb = (msg) => {
    return () => {
      props.callback(msg);
    };
  };
  return <h1 onClick={cb("传递给父组件的信息")}>{props.message}</h1>;
};

useContext结合Provider

import React, { useContext, useState } from "react";

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  const [theme, setTheme] = useState(themes.dark);
  const toggleTheme = () => {
    setTheme((v) => {
      return v === themes.dark ? themes.light : themes.dark;
    });
  };
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const state = useContext(ThemeContext);
  console.info(state, "state");
  return (
    <button
      onClick={state.toggleTheme}
      style={{
        background: state.theme.background,
        color: state.theme.foreground
      }}
    >
      I am styled by theme context!
    </button>
  );
}

export default App;