react+typescript实践总结

typescript语法参考
react参考

1、给绑定在dom上的方法传参

1.1定义

getDetailByBookId = (id: string) => {
  console.log(id)
}

1.2调用

<a data-id={book._id.$oid} 
onClick={this.getDetailByBookId.bind(this, book._id.$oid)}>
详情</a>

2、行内式css取值为变量的写法

style={{ display: `${this.state.custom_window_state}`,
 minWidth: `${this.state.minWidth_name}`}}

3、typescript语法编写react组件的代码基础结构

import * as React from 'react'
interface IState {
  test1?: string
  test2?: string
}
export interface IProps {
  empty?: any
 }
export default class CompontentName extends React.Component<IProps, IState> {
     // 这里初始化组件的全局变量
     map:any
     constructor(props: IProps, state: IState) {
          super(props)
          this.state = {
                 test1: '',
                 test2: ''
           }
      }
      render() {
           return (
              <div>
                   {dom or compontent}

              </div>
          )
     }
}

4、typescript中接口定义及使用

注意接口写在class外部,数据的使用在class内部

 // 定义IList接口 
interface IList {
  title: string
}

 // 使用IList接口
data: IList[] = [
    {
      title: 'Ant Design Title 1',
    },
    {
      title: 'Ant Design Title 2',
    },
    {
      title: 'Ant Design Title 3',
    },
    {
      title: 'Ant Design Title 4',
    }
  ]

5、react+typescript实现子组件调用父组件方法的效果

5.1组件结构

A组件里面引用了B组件,B组件里面引用了C组件
这里写图片描述

5.2实现步骤

如图C组件想要调用A组件中的方法-getBooks,首先C组件需要向外暴露接口

interface IProps {
  onComplete?: () => void
 }

并且在C组件需要的地方做该方法的调用

self.props.onComplete!()

此时B组件中
B组件对C组件的引用为:


<C onComplete={this.fatherComplete }/>

因为C组件想要调用的方法是在A组件中,所以B组件首先要实现C组件暴露的接口,同时向外继续暴露接口
B组件向外暴露接口

interface IProps {
  onComplete?: () => void
}

B组件实现C组件暴露的接口

fatherComplete = () => {
    this.props.onComplete!()
}

A组件中
A组件对B组件的引用为:

<B onComplete={this.addFormComplete} />

A组件继续实现B组件暴露给他的接口,此时C组件想要调用的getBooks方法就在该组件中就可以直接做this.getBooks的调用

addFormComplete = () => {
    this.getBooks()
 }

然后就可以实现C组件调用A组件中getBooks方法的效果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值