簡體   English   中英

如何在 React 中將 state 從孩子傳遞給父母?

[英]How to pass a state from a child to a parent in React?

您好,我有一個子組件和一個父組件。 在子組件中有一個 state。 state 必須在父組件中的類名之間切換。 我怎樣才能做到這一點?

 export function Parent({ children, darkMode }) { return ( <div className={cx(styles.component, darkMode && styles.darkMode)}> { children } </div> ) } export function Child() { const [darkMode, setDarkMode] = React.useState(false) return ( <header> <div className={styles.component}> <div className={styles.content}> <button onClick={colorSwith} className={styles.toggle}>Toggle</button> </div> </div> </header> ) function colorSwith() { setDarkMode(true) } }

使用 state 它是 1 個方向

不可能將 state 向上傳遞。 在下面的解決方案中,您可能需要綁定 function。 您可以通過克隆元素 React 方法修改孩子的道具。

export function Parent({ children, darkMode }) {
  const [darkMode, setDarkMode] = React.useState(false)
  return (
    <div className={cx(styles.component, darkMode && styles.darkMode)}>
      {React.cloneElement(children, { setDarkMode })}
    </div>
  )
}

export function Child(props) {
  return (
    <header>
      <div className={styles.component}>
        <div className={styles.content}>
          <button onClick={colorSwith} className={styles.toggle}>Toggle</button>
        </div>
      </div>
    </header>
  )
  function colorSwith() {
    props.setDarkMode(true)
  }
}

使用上下文 api

您還可以使用上下文 api 來訪問樹中任何位置的 state。 這樣,任何有權訪問上下文的組件都將在更改時重新呈現,並且數據可以傳遞和更改到樹中的任何點。

反應文檔中查看此示例

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

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

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

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

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

See how the context is set on the `App` level with a `Provider` and then changed in the `ThemeButton` with the `useContext` hook. This is a simple use case that seems simmilar to yours.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM