Tho*_*pré 5 javascript reactjs
我需要您的帮助,以更好地了解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不是函数”
我真的不明白为什么。你能帮助我吗?
您的问题可能来自您正在使用的 React 库的版本。
版本16.3.0(2018 年 3 月 29 日)React.createRef()可用
我得出这个答案是因为我已经测试了你的代码,React 版本 16.4.2 一切正常
这是演示: https: //codesandbox.io/s/jvzxmo4xky(我对您的 Button 组件做了假设)
| 归档时间: |
|
| 查看次数: |
2655 次 |
| 最近记录: |