javascript - React/JS - 数据建模
问题描述
我对 React 比较陌生。我在生产中的几个 Web 应用程序中使用 CRA。
以前,我曾在 Swift 中进行过广泛的工作。我熟悉 OOP 概念,我想以某种方式在 React 中实现模型。
样品容器:
class sampleContainer extends React.Component {
state = {
activity: null
}
sampleFun = (val1, val2) => {
...
}
componentDidMount() {
Axios.get(`url`)
.then(res => {
let activity = {
"name": res.data.data.name,
"type": res.data.data.type
}
this.setState({ activity })
})
.catch(e => {
// ...
});
}
render() {
return (
<React.Fragment>
{this.state.activity && (
<sampleComponent activity={this.state.activity}
sampleFun = {this.sampleFun}></sampleComponent>)
}
</React.Fragment>
)
}
}
示例组件:
class sampleComponent extends React.Component {
render() {
const { activity } = this.props
// Typing "activity." should suggest me "name" and "type"
return (
<React.Fragment>
{/* ... */}
</React.Fragment>
)
}
}
我正在使用 VSCode 编辑器。我想做的是,当我收到组件中的道具时,我想知道函数(“sampleFun”)和对象(在我的例子中是“活动”)的定义。
我知道这可以通过 TypeScript 完成,但是将我们的完整项目从 Javascript 移植到 Typescript 是不可能的。
请建议我如何实现它。
解决方案
是的,你可以PropTypes
在 React 中使用。
sampleComponent.propTypes = {
activity: PropTypes.shape({
name: PropTypes.string,
number: PropTypes.number
})
};
检查示例以供参考: 示例
推荐阅读
- python - 在 for 循环中分配变量名称
- nlp - 如何检查子动词 obj 三元组的真实性?
- angular - 如何以编程方式扩展primeng树表
- angular - Angular Material多对象拖放与调整大小问题
- docker-compose - 使用网格和 DNSRR 的 Docker 群网络延迟
- javascript - 在 v-data-table 中显示来自 Api 的数据,对象内的对象 vue js,vuetify
- css - 制作带有可点击背景的模态,无需 JavaScript
- javascript - React 在 useState 更改时添加表格单元格 flash 动画
- flutter - 如何检查密钥是否存在共享首选项值然后打开一个新屏幕
- javascript - 重写 javascript 函数以避免 JQuery.json 文件不被服务器读取