ReactJS:类型错误:this.ref.current.method不是一个函数。

8
我需要你帮忙更好地理解ReactJS中的引用机制。我创建了一个自定义组件,并尝试通过ref调用该组件的方法。但是,我得到一个错误,说我调用的不是一个函数。
在我的自定义组件"CountryInput"中,我有一个"sayHi"方法,仅通过console.log显示"hi"。
class CountryInput extends React.Component {
  sayHi(){
    console.log('hi');
  }

  render() {
    return(
      <h1>hello</h1>
    );
  }
};

这是我在组件中使用 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>
    );
  }

当我点击按钮时,出现以下错误:

"TypeError:this.ref.current.sayHi不是一个函数"

我真的不明白为什么会出现这个错误。你能帮我吗?


错误信息与您的代码不匹配。在消息中,它说this.ref,而在您的代码中是this.countryRef。您已经修复了代码但正在测试旧版本吗? - Daniel Hilgarth
我没有收到任何错误:https://codesandbox.io/s/3qq3zwn9v6 - Cristian S.
很有可能他正在使用不支持createRef()的旧版React,在16版本中它可以正常工作。https://codesandbox.io/s/m7v7nvrwly - 需要16.3+,但是它应该会抱怨React.createRef()不是一个函数... - Dimitar Christoff
在save()函数中添加一个调试器/断点,并检查countryRef.current - 我怀疑这不是你实际运行的代码,可能有一个高阶组件包装了CountryInput。 - Dimitar Christoff
我已经在CodeSandbox上更新了我的项目。顺便说一下,请创建一个评论而不是答案。 - You Nguyen
1个回答

0

1
我正在使用MaterialUI的withStyles来为我的组件应用样式,class CountryInput extends React.Component {...}; export default withStyles(componentStyle)(CountryInput); 看起来这可能是导致错误的原因:https://codesandbox.io/s/l6mxmq6vz - Thomas Dupré
1
好的,我解决了我的问题。当使用MaterialUI的withStyles时,我不能使用ref,我必须使用innerRef!非常感谢您的时间! - Thomas Dupré
谢谢你,Thomas。这个发现对我帮助很大。你能把它作为一个答案吗?因为这个回答并不是非常有帮助。 - Yuki
@ThomasDupré 你是怎么解决这个问题的?实际上,我的子组件中有 withStyles,而父组件中没有。 - Kramer
1
@Kramer,如果你正在使用 withStyles 包装导出你的子组件,那么你需要使用 innerRef={this.myref} 而不是 ref={this.myref}。 - Thomas Dupré

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接