我正在研究一个使用打字稿以及反应的项目,并且两者都是新手。我的问题是关于打字稿中的界面以及它与道具和状态的关系。实际发生了什么?除非声明接口属性和状态,否则我的应用程序根本不会运行,但是我通过react构造函数使用状态,并且我已经看到了一些示例,其中所有这些信息都将放入“接口MyProps”或“接口MyStates”中,因此请使用以下代码例子
"use strict";
import * as React from 'react'
import NavBar from './components/navbar.tsx'
import Jumbotron from './components/jumbotron.tsx';
import ContentPanel from './components/contentPanel.tsx';
import Footer from './components/footer.tsx';
interface MyProps {}
interface MyState {}
class Root extends React.Component <MyProps, MyState> {
constructor(props) {
super(props);
this.state = {
///some stuff in here
};
}
render() {
return (
<div>
<NavBar/>
<Jumbotron content={this.state.hero}/>
<ContentPanel content={this.state.whatIs}/>
<ContentPanel content={this.state.aboutOne}/>
<ContentPanel content={this.state.aboutTwo}/>
<ContentPanel content={this.state.testimonial}/>
<Footer content={this.state.footer}/>
</div>
)
}
}
export default Root;
(我已经删除了this.state中的内容,只是要在此处发布)。为什么需要界面?这样做的正确方法是什么,因为我认为我是用jsx而不是tsx的方式来考虑的。
您不清楚确切要问的是什么,但是:
props:是从组件的父级传递来的键/值对,并且组件不应更改其自身的props,仅应响应来自父级组件的props的更改。
状态:有点像道具,但是使用setState
方法可以在组件本身中对其进行更改。
render
道具或状态发生变化时,将调用该方法。
至于打字稿部分,它React.Component
采用两种类型作为泛型,一种用于道具,一种用于状态,您的示例应该看起来更像:
interface MyProps {}
interface MyState {
hero: string;
whatIs: string;
aboutOne: string;
aboutTwo: string;
testimonial: string;
footer: string;
}
class Root extends React.Component <MyProps, MyState> {
constructor(props) {
super(props);
this.state = {
// populate state fields according to props fields
};
}
render() {
return (
<div>
<NavBar/>
<Jumbotron content={ this.state.hero } />
<ContentPanel content={ this.state.whatIs } />
<ContentPanel content={ this.state.aboutOne } />
<ContentPanel content={ this.state.aboutTwo } />
<ContentPanel content={ this.state.testimonial } />
<Footer content={ this.state.footer } />
</div>
)
}
}
如您所见,该MyState
接口定义了稍后在组件this.state
成员中使用的字段(我使它们成为所有字符串,但它们可以是您想要的任何东西)。
我不确定这些字段是否真正需要处于状态而不是道具中,但这就是您需要做的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句