Javascript 如何从“;外部”;在我的书里?

Javascript 如何从“;外部”;在我的书里?,javascript,reactjs,dom,Javascript,Reactjs,Dom,为什么我不能从ReactJS中的“外部”访问组件方法?为什么不可能,有什么办法可以解决 以代码为例: var Parent = React.createClass({ render: function() { var child = <Child />; return ( <div> {child.someMethod()} // expect "bar", got a "no

为什么我不能从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);
var Parent=React.createClass({
render:function(){
var child=;
返回(
{child.someMethod()}//expect“bar”出现“not a function”错误。
);
}
});
var Child=React.createClass({
render:function(){
返回(
福
);
},
someMethod:function(){
返回“bar”;
}
});
React.renderComponent(,document.body);

React为您试图通过进行的操作提供了一个界面。为组件分配一个
ref
,其
current
属性将是您的自定义组件:

class父类扩展了React.class{
建造师(道具){
这个。_child=React.createRef();
}
componentDidMount(){
console.log(this._child.current.someMethod());//打印“bar”
}
render(){
返回(
);
}
}
注意:根据以下文档,仅当子组件声明为类时,此操作才有效:

更新2019-04-01:将示例更改为使用类并根据最新的React文档


更新2016-09-19:将示例更改为根据文档指南使用ref callback。

或者,如果Child上的方法是真正静态的(不是当前道具的产品,state),您可以在
statics
上定义它,然后像访问静态类方法一样访问它。例如:

var Child = React.createClass({
  statics: {
    someMethod: function() {
      return 'bar';
    }
  },
  // ...
});

console.log(Child.someMethod()) // bar

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

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

获取React外部React组件实例句柄的唯一方法是存储React.renderComponent.的返回值

由于反应0.12,API为。初始化myChild的有效代码如下所示:

var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();

你也可以这样做,不确定这是否是个好计划: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)
  }
}
类父级扩展组件{
handleClick(){
if(this.\u getAlert!==null){
这个。_getAlert()
}
}
render(){
返回(
{(getAlert,childScope)=>(
{!this.\u getAlert?this.\u getAlert=getAlert.bind(childScope):null}
)}
this.handleClick()}>单击我
);
}
}
类子扩展组件{
构造函数(){
超级();
this.state={count:0}
}
getAlert(){
警报(`Child function called state:${this.state.count}`);
this.setState({count:this.state.count+1});
}
render(){
返回this.props.children(this.getAlert,this)
}
}

如某些注释中所述,
ReactDOM.render
不再返回组件实例。在呈现组件的根以获取实例时,可以传入
ref
回调,如下所示:

// React code (jsx)
function MyWidget(el, refCb) {
    ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;

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

var ref=React.createRef()
变量父项=(
console.log(ref.current)}
);
React.renderComponent(父级、文档.body)
另一种简单的方法:

外部功能:

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);
  }
}

请参阅此处的完整教程:

这方面的源代码是。因此,两个子组件之间通信的唯一方法是在公共父组件?数据驱动组件上使用引用和代理方法。让一个子调用一个回调来更改其祖先中的数据,当该数据更改时,另一个子将获得新的
props
,并适当地重新渲染。@RossAllen,哈哈,是的,在这种情况下,您也必须删除分号。@HussienK如果函数没有返回值,我更喜欢使用块,这样下一个读取代码的开发人员就可以清楚地看到它的意图。将其更改为
{(child)=>this.\u child=child}
将创建一个始终返回
true
的函数,但React的
ref
属性不使用该值。也许您需要
Pubsub
?实际上它适用于react16。ReactDOM呈现方法返回对组件的引用(对于无状态组件,返回null)。
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);
  }
}