如果是用JavaScript开发可以忽略一切typescript的东西也是可以照常执行的
新建一个组件
interface Component<P = {}, S = {}, SS = any>{ // ..... }
组件基类的接口定义,P表示props,S表示state,SS未知,默认可以啥也不传
新建
import React, { Component } from 'react'; // 必须引入React
interface IHomeProps {
name: string;
}
interface IHomeState {
title: string
}
class Home extends Component<IHomeProps,IHomeState> {
public props: IHomeProps = {
name: 'props name'
}
public state: IHomeState = {
title: 'home state title'
}
constructor(props: IHomeProps, state: IHomeState) {
super(props, state);
}
render() {
return (
<div className="home-component-root">
<p>{this.state.title}</p>
<p>{this.props.name}</p>
</div>
);
}
}
export default Home;
使用Home组件
import React, { Component } from 'react';
import './App.css';
import Home from './pages/home';
import { LifeCycleComponent } from './pages/life-cycle';
import { ChildComponent } from './pages/child';
class App extends Component<any, {count: number}> {
count: number = 1;
state = { count: 1};
constructor(props: any, context: any) {
super(props, context);
}
onclick() {
this.setState({
count: this.state.count+1
});
}
render() {
return (
<div className="app-root">
<Home name="sss"></Home>
<Home name="sss" />
</div>
);
}
}
export default App;
无组件嵌套可以直接用自闭标签
组件中事件绑定this指向问题
class App extends Component<any, {count: number}> {
onclick() { console.log(this) }
render() {
return (<button onClick={this.onclick.bind(this)}>click</button>);
}
}
this指向App这个对象
class App extends Component<any, {count: number}> {
onclick() { console.log(this) }
render() {
return (<button onClick={this.onclick}>click</button>);
}
}
this指向window这个对象
class App extends Component<any, {count: number}> {
constructor(props, state) { super(props,state); this.onclick.bind(this) }
onclick() { console.log(this) }
render() {
return (<button onClick={this.onclick}>click</button>);
}
}
this指向App这个对象
组件嵌套
父组件
import React, { Component } from 'react';
export interface LifeCycleProps{
count: number;
}
export class LifeCycleComponent extends Component<LifeCycleProps> {
protected title: string = 'LifeCycle works!';
public render() {
return (
<div>
{this.title}{this.props.count}
<div>
{this.props.children}
</div>
</div>
);
}
}
子组件
import React, { Component } from 'react';
export class ChildComponent extends Component {
render() {
return (
<div>child component works!</div>
);
}
}
嵌套
<LifeCycleComponent count={this.state.count} >
<ChildComponent></ChildComponent>
</LifeCycleComponent>
组件包含的内容其实是通过props.children传递的,并且props.children为数组,如果要针对特定组件放到特定位置,可用用props传递,然后在父组件的render中输出{this.props.childComponent}, 如果父组件要传递值给子组件,可以在父组件获取子组件实例设置值
修改state值
修改state的值需要调用this.setState({…});才能让dom从新渲染,或者直接修改然后调用this.setState({});也可以触发渲染。
某些情况下可以强制重新渲染this.forceUpdate();
修改props
一般情况一个是不予许子组件修改props的值,应该是触发父组件来改变然后传递到子组件,导致重新渲染。