react+typescript中使用ref

react+typescript / 1608人浏览 / 0人评论

1.首先在constructor 上面定义

private bgImage: React.RefObject<HTMLDivElement>;

2.然后在constructor里面定义

this.bgImage = React.createRef();

3.绑定到dom上

<div ref={this.bgImage}>

4.使用(比如在生命周期里面使用)

componentDidMount() {
 this.bgImage.current && (this.bgImage.current.style.background = "#fff000");
}

看效果

image.png


完整的组件dog代码

import React, {Component} from 'react';

type dogType = {

 age: number,
 height: number,
 dogFrirends: string[],

}
type proType = {
 color: string,
 name: string,
}


class Dog extends Component<proType, dogType> {
 private bgImage: React.RefObject<HTMLDivElement>;

 constructor(props: proType) {
   super(props);
   this.bgImage = React.createRef();
   this.state = {
     age: 1,
     height: 30,
     dogFrirends: ['a', 'b']
   }


 }

 static defaultProps: proType = {
   name: "xiaohong",
   color: "red",
 }

 componentDidMount() {
   this.bgImage.current && (this.bgImage.current.style.background = "#fff000");
 }

 render() {
   const {age, height, dogFrirends} = this.state;
   const {color, name} = this.props;
   return <>
     <div ref={this.bgImage}>

       狗的名字:{name}
       <br/>
       狗的颜色:{color}
       <br/>
       狗的年龄:{age}
       <br/>
       狗的身高:{height}
       <br/>
       狗友:
       {dogFrirends.map((friend: string, index: number) => (<li key={index}>{friend}</li>))}

     </div>
     <button onClick={() => {
       this.up()
     }}>狗子成长了
     </button>
   </>;
 }

 up = (): void => {
   let {age, height, dogFrirends} = this.state;
   age = age + 1;
   height = height + 10;
   dogFrirends = [...dogFrirends, 'friend' + dogFrirends.length]
   this.setState({
     age,
     height,
     dogFrirends
   })
 }

}

export default Dog;



好好学习,天天向上!


0 条评论

还没有人发表评论

发表评论 取消回复

记住我的信息,方便下次评论
有人回复时邮件通知我