如何从ReactJS的“外部”访问组件方法?

为什么我不能从ReactJS的“外部”访问组件方法?为什么不可能,有什么办法解决呢?

考虑以下代码:

var Parent = React.createClass({
    render: function() {
        var child = <Child />;
        return (
            <div>
                {child.someMethod()} // expect "bar", got a "not a function" error.
            </div>
        );
    }
});

var Child = React.createClass({
    render: function() {
        return (
            <div>
                foo
            </div>
        );
    },
    someMethod: function() {
        return 'bar';
    }
});

React.renderComponent(<Parent />, document.body);
Eva西里2020/03/11 11:47:15

另一种简单的方法:

外部功能:

function funx(functionEvents, params) {
  console.log("events of funx function: ", functionEvents);
  console.log("this of component: ", this);
  console.log("params: ", params);
  thisFunction.persist();
}

绑定它:

constructor(props) {
   super(props);
    this.state = {};
    this.funxBinded = funx.bind(this);
  }
}

Please see complete tutorial here: How to use "this" of a React Component from outside?

逆天Itachi2020/03/11 11:47:15

可以这样做,不确定是否是好的计划:D

class Parent extends Component {
  handleClick() {
    if (this._getAlert !== null) {
      this._getAlert()
    }
  }

  render() {
    return (
      <div>
        <Child>
        {(getAlert, childScope) => (
          <span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
        )}
        </Child>
        <button onClick={() => this.handleClick()}> Click me</button>
      </div>
      );
    }
  }

class Child extends Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  getAlert() {
    alert(`Child function called state: ${this.state.count}`);
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return this.props.children(this.getAlert, this)
  }
}
小宇宙神无2020/03/11 11:47:15

如果要从React外部调用组件上的函数,可以在renderComponent的返回值上调用它们:

var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();

获取React之外的React Component实例的句柄的唯一方法是存储React.renderComponent的返回值。来源

逆天JinJin2020/03/11 11:47:15

从React 0.12开始,API进行了少许更改初始化myChild的有效代码如下:

var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();
A小卤蛋Pro2020/03/11 11:47:15

从React 16.3开始 React.createRef可以使用(用于ref.current访问)

var ref = React.createRef()

var parent = <div><Child ref={ref} /> <button onClick={e=>console.log(ref.current)}</div>

React.renderComponent(parent, document.body)