react中TS类组件的写法

类组件最多的就是Typescript接口类型的应用,限制组件状态或者属性符合接口定义

  1. state.tsx


interface IState {
    name: string
}

export default class App extends Component<约定属性,约定状态>
export default class App extends Component<any,IState> { // 属性不约束,状态约束
    state = {
        name: 'xxx' // 这时就会提示类型校验
    }
    render() {
        return (
            // ...
            setState({name: "yyy"})
            // ...
        )
    }
}
 

  1. todo.tsx

import React, { Component } from 'react'

interface IState{

list:string[]

}

export default class ClassTest extends Component<any,IState> {

state={

name:'sb',

list:[]

}

change=()=>{

console.log(this.inputRef.current?.value)

this.setState({

list:[...this.state.list,(this.inputRef.current as HTMLInputElement).value]

})

}

inputRef = React.createRef<HTMLInputElement>()

render() {

return (

<div>

<input ref={this.inputRef}></input>

<button onClick={this.change}>name</button>

<ul>

{

this.state.list.map((item,index)=>

<li key={index}>{item}</li>

)

}

</ul>

</div>

)

}

}

  1. props.tsx
export default class App extends Component {
    render() {
        return (
            <div>
                <Child name="aaa">
            </div>
        )
    }
}
interface IProps {
    name: string
}
class Child extends Component<IProps, any> {
    render() {
        return <div>
            {this.props.name}
        </div>
    }
}
  1. drawer.tsx
export default class App extends Component {
  state = {
    isShow: true,
  };
  render() {
    return (
      <div>
        app
        <Navbar
          title="first page"
          cb={() => {
            this.setState({
              isShow: !this.state.isShow,
            });
          }}
        />
        {this.state.isShow && <Sidebar></Sidebar>}
      </div>
    );
  }
}
interface IProps {
  title: string;
  cb: () => void;
}
class Navbar extends Component<IProps, any> {
  render() {
    return (
      <div>
        Navbar-{this.props.title}
        <button
          onClick={() => {
            this.props.cb();
          }}
        ></button>
      </div>
    );
  }
}
class Sidebar extends Component {
  render() {
    return <div>Sidebar</div>;
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值