cec*_*ode 28 jsx typescript reactjs tsx
我正在开发一个使用打字稿以及反应的项目,对两者都是新手.我的问题是关于打字稿中的界面以及它与道具和状态的关系.究竟发生了什么?除非我声明接口道具和状态,否则我的应用程序根本不会运行,但是我通过反应构造函数使用状态,并且我已经看到所有这些信息将进入"接口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;
Run Code Online (Sandbox Code Playgroud)
(我已经删除了this.state中的内容,只是为了在这里发布).为什么我需要界面?这样做的正确方法是什么,因为我认为我是以jsx方式而不是tsx方式考虑这个问题.
Nit*_*mer 31
目前尚不清楚你究竟在问什么,但是:
props:是从组件的父级传递的键/值对,组件不应该更改它自己的props,只对来自父组件的props的更改做出反应.
state:有点像道具但是它们在组件本身中使用该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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,MyState界面定义了稍后在组件this.state成员中使用的字段(我将它们全部变为字符串,但它们可以是您想要的任何字符串).
我不确定这些领域是否真的需要处于状态而不是道具,但是你要求制造.
| 归档时间: |
|
| 查看次数: |
36455 次 |
| 最近记录: |