繁体   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