React通信方式

126 阅读1分钟

1.props父子通信

2.回调函数,子父通信

3.变量提升,兄弟组建通信

4.Context跨组建通信

5.redux共享数据通信

Context跨组建通信

基于props做组件的跨层级数据传递是非常困难并且麻烦的,中间层组件要为了传递数据添加一些无用的props。

context做的事情就是创建一个上下文对象,并且对外暴露提供者(通常在组件树中上层的位置)和消费者,在上下文之内的所有子组件,都可以访问这个上下文环境之内的数据,并且不用通过props。可以理解为有一个集中管理state的对象,并限定了这个对象可访问的范围,在范围之内的子组件都能获取到它内部的值。

juejin.cn/post/684490… 极好的示例

创建一个上下文 
import React from 'react' 
const ThemeContext = React.createContext() 
export const ThemeProvider = ThemeContext.Provider 
export const ThemeConsumer = ThemeContext.Consumer 
// 提供者提供数据 提供者一般位于比较上边的层级,ThemeProvider 接受的value就是它要提供的上下文对象。 
// index.js 
import { ThemeProvider } from './context' 
render() {
  const { theme } = this.state 
  return <ThemeProvider value={{ themeColor: theme }}> <Page/> </ThemeProvider> 
}

// 消费者获取数据 
// 在这里,消费者使用了renderProps模式,Consumer会将上下文的数据作为参数传入renderProps渲染的 函数之内,所以这个函数内才可以访问上下文的数据。 
import React from 'react' 
import { ThemeConsumer } from './context' 
class Title extends React.Component { 
  render() { 
    return <ThemeConsumer> { 
      theme => <h1 style={{ color: theme.themeColor }}> title </h1> 
      } 
    </ThemeConsumer> 
  } 
}

变量提升,兄弟组建通信

function Counter({ count, onIncrementClick }) {
  return <button onClick={onIncrementClick}>{count}</button>; // 操作行为
}
function CountDisplay({ count }) {
  return <div>The current counter count is {count}</div>; // 状态
}
function App() {
  const [count, setCount] = React.useState(0); // 将状态提升到父组件中,通过 props 传递
  const increment = () => setCount((c) => c + 1);
  return (
    <div>
      {" "}
      <CountDisplay count={count} />{" "}
      <Counter count={count} onIncrementClick={increment} />{" "}
    </div>
  );
}