# props.children

props.children是组件的所有子节点

<MiddleComponent name={"zs"} age={20}>
   31321
</MiddleComponent>

class MiddleComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log(props); // {name: "zs", age: 20, children: "31321"}
  }
}
1
2
3
4
5
6
7
8
9
10

App.jsx

import { AppContext, context } from "./context";

export default function App() {
  return (
    <AppContext.Provider value={context}>
      <div className="App">
        <Main />
        <Child />
      </div>
    </AppContext.Provider>
  );
}

function Child() {
  return (
    <div>
      <div>345</div>
      <AppContext.Consumer>{(val) => val.username}</AppContext.Consumer>
    </div>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

context.js

import React from "react";
export const AppContext = React.createContext({});
export const context = {
  username: "ls"
};
1
2
3
4
5

# context与函数组件使用

useContext

export const MyContext = React.createContext({
  name: "zs",
  age: 22
});

export default function App() {
  return (
    <MyContext.Provider value={{ name: "zsss", age: 30 }}>
      <div className="App">
        <Main />
        <Child />
      </div>
    </MyContext.Provider>
  );
}

function Child() {
  const ctx = useContext(MyContext);
  console.log(ctx.age);
  return (
    <>
      <div>{ctx.name}</div>
    </>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 函数调用向上传递-子传父

export default function Father() {
  let [num, setNum] = useState(0)
  return (
    <>
      <div num={num}>向上传递展示的值: {num}</div>
      <button onClick={() => setNum(++num)}>向下传递++</button>
      <Son
        son-num={num}
        onMy={(val) => {
          console.log('son', val)
          setNum(num - val)
        }}
      ></Son>
    </>
  )
}

function Son(props) {
  console.log('props: ', props)
  const { onMy } = props
  const [sonState] = useState(2)
  return (
    <>
      <div>向下传递展示的值: {props['son-num']}</div>
      <button onClick={() => onMy(sonState)}>向上传递--</button>
    </>
  )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

在React中只有通过setState修改的数据,视图才会实时更新

# 父组件调用子组件的方法

使用函数回调和 useRef

import React, { useRef } from 'react';

function ChildComponent({ onChildMethod }) {
  // 子组件中的方法
  const doSomething = () => {
    alert('子组件执行了某个操作');
  };

  // 当需要执行子组件方法时,调用父组件传递的方法
  onChildMethod(doSomething);

  return <div>子组件</div>;
}

function ParentComponent() {
  const childRef = useRef();

  const callChildMethod = (method) => {
    if (childRef.current) {
      method();
    }
  };

  return (
    <div>
      <ChildComponent onChildMethod={callChildMethod} />
      <button onClick={() => callChildMethod()}>调用子组件方法</button>
    </div>
  );
}

export default ParentComponent;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

还可以使用 forwardRef 和 useImperativeHandle