3. React组件通信的两种方式

3. React组件通信

3.1 层层传递

image-20240823095342512

这里举一个例子,一个简单的点击按钮数字增加的例子。我们有三个组件 Father Child GrandChild.

GrandChild有一个按钮,但是它没有自己的count数值自己的点击按钮的方法,需要Father组件一层层传下来,我们要实现的效果是GrandChild按钮点击的时候Father组件Child组件和GrandChild组件一起增加。

image-20240823104535021

Father有两个遗产 一个是count属性,另一个是祖传方法handleIncrement

Father.jsx

import React, { useState } from 'react';
import Child from './Child';

const Father = () => {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Father Component</h1>
      <p>
        Count:
        {count}
      </p>
      <Child count={count} handleIncrement={handleIncrement} />
    </div>
  );
};

export default Father;

Child.jsx

import React from 'react';
import PropTypes from 'prop-types';
import GrandChild from './GrandChild';

// 从Father组件中获取count和handleIncrement
const Child = ({ count, handleIncrement }) => (
  <div>
    <h2>Child Component</h2>
    <p>
      Count:
      {count}
    </p>
    <GrandChild count={count} handleIncrement={handleIncrement} />
  </div>
);
// 增加数据验证
Child.propTypes = {
  count: PropTypes.number.isRequired,
  handleIncrement: PropTypes.func.isRequired,
};
export default Child;

GrandChild.jsx

import React from 'react';
import PropTypes from 'prop-types';

// 从Child组件中获取count和handleIncrement
const GrandChild = ({ count, handleIncrement }) => (
  <div>
    <h3>GrandChild Component</h3>
    <p>
      Count:
      {count}
    </p>
    <button onClick={handleIncrement} type="button">Increment</button>
  </div>
);

GrandChild.propTypes = {
  count: PropTypes.number.isRequired,
  handleIncrement: PropTypes.func.isRequired,
};
export default GrandChild;

3.2 使用Context

我们在App.jsx声明一个Context,然后在其子组件,或者在其第n代子组件中都可以使用这个Context,假设我们的页面需要一个主题变量,我们需要App.jsx的所有子孙组件与App.jsx中的主题保持一致,我们就可以使用Context

App.jsx

import React, { createContext } from 'react';
import { HashRouter as Router, Switch, Route } from 'react-router-dom';
import Loadable from 'react-loadable';
import ReactPlaceholder from 'react-placeholder';
import { RectShape, RoundShape } from 'react-placeholder/lib/placeholders';
import TopMenu from './components/TopMenu';
import Home from './routes/Home';
import About from './routes/About';
import NotFound from './routes/NotFound';
import './styles/app.less';

export const ThemeContext = createContext();
class App extends React.PureComponent {
  render() {
    return (
      <>
        <ThemeContext.Provider value="dark"> //在这里声明主题context 被Provider包裹的所有子组件都能接收到组件的主题
          <Router>
            <div className="f-dfc">
              <TopMenu />
              <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/home" component={Home} />
                <Route path="/todo" component={Todo} />
                <Route path="/chart" component={Chart} />
                <Route path="/about" component={About} />
                <Route path="*" component={NotFound} />
              </Switch>
            </div>
          </Router>
        </ThemeContext.Provider>
      </>
    );
  }
}
export default App;

Home.jsx

先从祖先文件里获取这个ThemeContext 然后使用useContext获取theme

/* eslint-disable import/no-cycle */
import React, { useContext } from 'react';
import { connect } from 'react-redux';
import { ThemeContext } from '../App'; 

const Home = () => {
  const theme = useContext(ThemeContext);
  return (
    <div className="home">
      <h1 className="slogen">
        {`使用context获取app的主题为 ${theme}`}
        <br />
        <Input label="姓名" />
        <Input2 label="年龄" />
      </h1>
    </div>
  );
};
const mapStateToProps = state => ({ greetings: state.greetings });
export default connect(mapStateToProps)(Home);

Home.jsx

也可以使用ThemeContext.Consumer

/* eslint-disable import/no-cycle */
import React from 'react';
import { connect } from 'react-redux';
//  import ProgramLanguage from '@/components/ProgramLanguage';
import Input from '@/components/ClassComponent';
import Input2 from '@/components/FuctionComponent';
import { ThemeContext } from '../App';
import Father from '../components/ComponentsComunication/Father';

const Home = () => (
  <ThemeContext.Consumer>
    {theme => (
      <div className="home">
        <h1 className="slogen">
          {`使用context获取app的主题为 ${theme}`}
          <br />
          <Father />

          {/* <ProgramLanguage /> */}
          <Input label="姓名" />
          <Input2 label="年龄" />
        </h1>
      </div>
    )}
  </ThemeContext.Consumer>
);

// window.addEventListener('keydown',(evt)=>{
//   if(evt.keyCode === 27){
//     message.info('esc clicked');
//     // 在终端内可阻止esc默认跳转到上一页
//     // 最好不要加在window上,这里仅仅作为测试
//     evt.preventDefault();
//   }
// })

const mapStateToProps = state => ({ greetings: state.greetings });

export default connect(mapStateToProps)(Home);

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜业

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值