1.组件数据传递问题
数据传递:A(顶级组件)-》B组件(子组件)、C组件(孙子组件)…很多组件
这样得通过props层层传递到下面的组件
还有另一种解决方法,即通过全局对象来解决,使用Provider可以解决数据层层传递和每个组件都要传props的问题;
2.props传递例子
学习react-环境&手脚架&页面&路由
在上一节的路由配置文件中,HomePage传递了name值
// Router.tsx
const routes: RouteObject[] = [
{
path: '/',
element:<HomePage name={
"test"} /> //<Navigate to='home/one' /> // 重定向
},
{
path: 'login',
element: <LoginPage name={
"login"} />
},
// 未匹配到页面
{
path: '*',
element: <NotFoundPage name={
"notfound"} />
}
]
在这一节中,创建MainPage,并在HomePage中引用
// MainMeta.tsx
export interface MainProp extends MetaProp{
}
export interface MainState extends MetaState{
}
// MainPage.tsx
class MainPage extends Component<MainProp, MainState> {
constructor(props: MainProp) {
super(props);
this.state = {
count: 0 };
}
render() {
const {
name } = this.props; //解构赋值
return <h1>Hello main page, {
name}!</h1>;
}
}
MainPage在HomePage中引用,并用props继续给MainPage传递name值
// MainPage.tsx
class MainPage extends Component<MainProp, MainState> {
constructor(props: MainProp) {
super(props);
this.state = {
count: 0 };
}
render() {
const {
name } = this.props; //解构赋值
return <h1>Hello main page, {
name}!</h1>;
}
}
如下图props的name字段,值为test,一层层传递
3.用全局对象context
1. state共同维护context(function模式)
首先创造Global.tsx和ConfigProvider.tsx
// Global.tsx
class Global {
constructor() {
}
count = 0;
name = 'react';
loading =