React考点清单

为什么 JSX 中的组件名要以大写字母开头?

因为 React 要知道当前渲染的是组件还是 HTML 元素。

React 组件间有那些通信方式?

父组件向子组件通信
1、 通过 props 传递

子组件向父组件通信
1、 主动调用通过 props 传过来的方法,并将想要传递的信息,作为参数,传递到父组件的作用域中

跨层级通信
1、 使用 react 自带的 Context 进行通信,createContext 创建上下文, useContext 使用上下文。

参考下面代码:

import React, {
    createContext, useContext } from 'react';

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

const ThemeContext = createContext(themes.light);

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

function Toolbar() {
   
  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>
  );
}

export default App;

2、使用 Redux 或者 Mobx 等状态管理库

3、使用订阅发布模式

React 父组件如何调用子组件中的方法?

1、如果是在方法组件中调用子组件(>= react@16.8),可以使用 useRef 和 useImperativeHandle:

const {
    forwardRef, useRef, useImperativeHandle } = React;

const Child = forwardRef((props, ref) => {
   
  useImperativeHandle(ref, () => ({
   
    getAlert() {
   
      alert("getAlert from Child");
    }
  }));
  return <h1>Hi</h1>;
});

const Parent = () => {
   
  const childRef = useRef();
  return (
    <div>
      <Child ref={
   child
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

咩咩羊10

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

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

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

打赏作者

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

抵扣说明:

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

余额充值