网页设计作业个人网站,全国建设部网站官网,建设游戏网站需要哪些设备,深圳南山企业网站建设好 刚讲完组件 那么 这次 我们来看一下 数据传递的 props
还是上文的案例 例如 我们想将 title 传给Hello组件 之前我们可以直接这样 以一个标签属性的形式传过去
而我们在子组件中 这样去使用 但现在 我们从编辑器中都可以看出 这种写法已经不行了
然后 我们将 hello 组件…好 刚讲完组件 那么 这次 我们来看一下 数据传递的 props
还是上文的案例 例如 我们想将 title 传给Hello组件 之前我们可以直接这样 以一个标签属性的形式传过去
而我们在子组件中 这样去使用 但现在 我们从编辑器中都可以看出 这种写法已经不行了
然后 我们将 hello 组件改成这样
import * as React from react;interface IProps {title: string
}export default class hello extends React.ComponentIProps {public constructor(props:any){super(props);}public render() {return (div{ this.props.title }/div)}
}其中 最大的不同在于 我们定义了一个接口 IProps 规定里面要有一个 string字符串类型的字段 叫title 然后 挂到 react的Component上进行泛型 然后 这是 我们的父子组件就都不报错了 当然 我们可以传多个数据
这里 我们给子组件一个 age 数字 20 然后子组件规定一下类型 这里 我们用了Number 说他是个数字类型 那么 我们父组件尝试改成 字符串试试 很显然 这里就报错了 这也是Ts的一个意义 能够加强代码的规范和可读性
好 最后 父组件代码如下
import Hello from ./components/hello;function App() {return (div classNameApphello React TypescriptHello title 高阶组件 age { 20 } //div);
}export default App;子组件代码
import * as React from react;interface IProps {title: string,age: number
}export default class hello extends React.ComponentIProps,any {public constructor(props:any){super(props);}public render() {return (divdiv{ this.props.title }/divdiv{ this.props.age }/div/div)}
}然后 我们运行项目 也是没有任何问题