创建react项目

创建 react 项目 使用 create-react-app __name 创建 react 项目 安装依赖 安装路由: npm i react-router-dom 安装 axios:npm i axios 安装 antd sass 等 React hooks 传参 1、使用 props 传参

创建 react 项目

使用 create-react-app __name 创建 react 项目

安装依赖

安装路由: npm i react-router-dom

安装 axios:npm i axios

安装 antd sass 等

React hooks 传参

1、使用 props 传参

使用 props 传递参数是 React 中最常见的方式。可以通过在父组件中定义 props 并将其传递给子组件。子组件可以通过 props 属性来访问传递的参数。

// 父组件
function ParentComponent() {
  const name = "John Doe";
  cosnt handleClick = (e)=>{
	console.log(e)
}
  return (
    <ChildComponent name={name} handleClick={handleClick}/>
  );
}

// 子组件
function ChildComponent(props) {
const {name,handleClick} = props
  return (
    <div>
      <p>My name is {name}</p>
      <button onClick={handleClick}></button>
    </div>
  );
}

2、使用 Context 传参

使用 Context 可以跨越组件树传递参数,而不必显式地通过 props 传递。可以使用createContext函数创建一个 Context 对象,并通过Provider组件将值传递给子组件。子组件可以通过useContext Hook 来获取 Context 的值。

// 创建一个Context对象
const NameContext = React.createContext();

// 父组件
function ParentComponent() {
  const name = "John Doe";
  return (
    <NameContext.Provider value={name}>
      <ChildComponent />
    </NameContext.Provider>
  );
}

// 子组件
function ChildComponent() {
  const name = useContext(NameContext);
  return (
    <div>
      <p>My name is {name}</p>
    </div>
  );
}


react hooks

在函数组件中没有生命周期,为了解决这一问题,react 在函数组件中可以使用 hooks 来对函数组件的业务逻辑

1、useState()和 useEffect()

使用 useState()创建一个响应式数据,在其发生变化时,页面上也会发生相对应的重新渲染

import {useSate} from "react"

export default function app () {
	const [state,setSate] = useSate()
	// 使用setState以改变state的状态
	setSate(xxx)
	// 在state状态发生改变时,rander函数会重新执行
	// 但是此前在funcation app 中,state的值还未发生变化
	// 需要使用useEffect hook来监听
}
LICENSED UNDER CC BY-NC-SA 4.0
Comment