1

react项目中有两个组件。1,父母 2,孩子

现在,我想在 Parent 组件中使用 childMethod 。在stackoverflow的一些页面中,大家都说refs是有效的。但在我的项目中,它不起作用。

class Parent extends Component {
 parentMethod(){
   this.refs.child.childMethod();
 }

 render() {
  return (
    <Child ref='child'/>
  );
 }
}



class Child extends Component {
 childMethod() {
    alert('You made it!');
 }
 render() {
  return (
    <h1 ref="hello">Hello</h1>
  );
 }
}

当我使用上述代码时,浏览器控制台中有一个错误代码。 _this3.refs.child.childMethod 不是函数

我想使用子方法,所以我有两个问题。1、什么是“_this3”?如何正确使用 refs?2、你有什么其他的想法吗?

4

1 回答 1

0
class Parent extends React.Component {

  constructor(props) {
    super(props);

    // binding methods to the class so they don't lose 'this'
    // when invoked from another environment.
    this.parentMethod = this.parentMethod.bind(this);
    this.setChildRef = this.setChildRef.bind(this);
  }

  parentMethod() {
    this.childNode.childMethod();
  }

  // intentionally avoided using an arrow fuction inside JSX
  // for we don't want a new anonymous fn created on every render.
  setChildRef(node) { // receives reference to component as argument
    this.childNode = node;
  }

  render() {
    return (
      <div>
        <Child ref={this.setChildRef}/>
        <button onClick={this.parentMethod}>Parent Button - Click me :)</button>
      </div>
    );
  }
}

class Child extends React.Component {
  childMethod() {
    alert('You made it!');
  }

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

工作小提琴:https ://jsfiddle.net/free_soul/9vrLrw8h/


  1. 什么是“_this3”?

    可能是您在调试时可能会在浏览器中看到的变量。它只是代表一个执行上下文。

  2. 如何正确使用 refs?

    最好将ref视为回调属性,不再依赖于 refs 对象。如果您确实使用了 refs 对象,请避免访问后代组件的 refs。您应该将refs其视为私有访问器,而不是组件 API 的一部分。仅将组件实例上公开的方法视为其公共 API。

于 2016-11-26T10:57:37.363 回答