小编Tho*_*pré的帖子

ReactJS:TypeError:this.ref.current.method不是一个函数

我需要您的帮助,以更好地了解ReactJS的ref机制。我制作了一个自定义组件,并试图通过ref调用此组件的方法。但是,我得到这个错误,即我所调用的不是函数

我的自定义组件“ CountryInput”中有一个“ sayHi”方法,仅在console.log中显示“ hi”

class CountryInput extends React.Component {
  sayHi(){
    console.log('hi');
  }

  render() {
    return(
      <h1>hello</h1>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)

这是我在其中使用ref的组件:

class MyComponent extends Component {
constructor(props) {
    super(props);
    this.countryRef = React.createRef();
  }

  save(){
    this.countryRef.current.sayHi();
  }

  render() {
    const {address, classes}= this.props;
    return (
        <React.Fragment>
        <CountryInput ref={this.countryRef} />
          <Button className={classes.button} onClick={()=>this.save()}>
            Enregister
          </Button>
        </React.Fragment>
    );
  }
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,出现此错误:

“ TypeError:this.ref.current.sayHi不是函数”

我真的不明白为什么。你能帮助我吗?

javascript reactjs

5
推荐指数
1
解决办法
2655
查看次数

标签 统计

javascript ×1

reactjs ×1