首页 > 解决方案 > 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 是不可能的。

请建议我如何实现它。

标签: javascriptreactjstypescript

解决方案


是的,你可以PropTypes在 React 中使用。

sampleComponent.propTypes = {
activity: PropTypes.shape({
    name: PropTypes.string,
    number: PropTypes.number
    })
};

检查示例以供参考: 示例


推荐阅读