首页 新闻 赞助 找找看

react使用ts时报错了,求解答

0
悬赏园豆:5 [已解决问题] 解决于 2020-07-07 19:11

我在尝试 react 中使用 ts,当我创建 ref 时报错了,请问该怎么解决?谢谢!
Property 'ref' does not exist on type 'ForwardRef'. Did you mean 'refs'?ts(2551)
index.d.ts(507, 9): 'refs' is declared here.

class ForwardRef extends Component {
  constructor(props){
    super(props);
    this.ref = createRef();
  }

  render(){
    return (
      <FancyButton ref={this.ref}>Click me!</FancyButton>
    );
  }
}
zanetti的主页 zanetti | 初学一级 | 园豆:128
提问于:2020-07-05 23:11
< >
分享
最佳答案
0

在ForwardRef里面增加一个ref字段?你这this.ref,你没有ref这个字段啊。

收获园豆:5
顾晓北 | 专家六级 |园豆:10844 | 2020-07-06 09:58

我该怎么添加 ref 字段呢?在 react js 里是可以这么写的,求教~

zanetti | 园豆:128 (初学一级) | 2020-07-06 18:23

@zanetti:

class ForwardRef extends Component {
  ref: any;
  constructor(props){
    super(props);
    this.ref = createRef();
  }

  render(){
    return (
      <FancyButton ref={this.ref}>Click me!</FancyButton>
    );
  }
}

实际上命名这个,一般会加前缀

class ForwardRef extends Component {
  buttonRef: any;
  constructor(props){
    super(props);
    this.buttonRef = createRef();
  }

  render(){
    return (
      <FancyButton ref={this.buttonRef}>Click me!</FancyButton>
    );
  }
}
顾晓北 | 园豆:10844 (专家六级) | 2020-07-06 18:58

@顾晓北: 非常感谢!原来只要定义一下类型就可以了。

zanetti | 园豆:128 (初学一级) | 2020-07-07 19:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册