我正在尝试在另一个 onClick 事件函数上触发点击按钮。
Error : Uncaught TypeError: this.clickBack.current.click is not a function
React 版本是 16.8.6
constructor(props) {
super(props)
this.clickBack = React.createRef();
this.startInterview = this.startInterview.bind(this);
}
startInterview(){
console.log('hello') // output : hello
console.log(this.clickBack.current); // output : Button {props: {…}, context: {…}, refs: {…}, updater: {…}, onClick: ƒ, …}
this.clickBack.current.click(); // output : Uncaught TypeError: this.clickBack.current.click is not a function
}
在渲染->返回方法
<Link to={backLink}>
<Button ref={this.clickBack}> Back</Button>
</Link>
<Button onClick={this.startInterview}> Start Interview</Button>
最佳答案
正如我们在 console.log 中看到的那样,ref 引用的是 Button 组件,而不是 dom 元素。如果此 Button 是您定义的组件,您应该通过 prop 将您的 ref 传递给 button
dom元素例如
<Button innerRef={this.clickBack}...>
Button.js
...
<button ref={this.props.innerRef}
(这里的 innerRef 是一个任意的名字)
关于javascript - onClick触发点击报错: current.点击不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176360/