Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何调用子组件的实例方法?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何调用子组件的实例方法?

Javascript 如何调用子组件的实例方法?,javascript,reactjs,Javascript,Reactjs,将回调函数作为道具传递给子组件很简单,但反之亦然 如何调用子组件的实例方法? 在组件中,我需要调用组件的这个.bar实例方法 class Parent extends React.Component { render() { return ( <Child /> ) } } class Child extends React.Component { constructor( props ) {

将回调函数作为道具传递给子组件很简单,但反之亦然

如何调用子组件的实例方法?

组件中,我需要调用
组件的
这个.bar
实例方法

class Parent extends React.Component {
    render() {
        return (
            <Child />
        )
    }
}

class Child extends React.Component {
    constructor( props ) {
        super( props );
        this.bar = () => console.log('foo');

    }

}
类父级扩展React.Component{
render(){
返回(
)
}
}
子类扩展了React.Component{
建造师(道具){
超级(道具);
this.bar=()=>console.log('foo');
}
}

您可以使用
refs
执行此操作

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  componentDidMount() {
    this.childRef.current.bar()
  }

  render() {
    return (
      <Child ref={this.childRef} />
    );
  }
}

class Child extends React.Component {
  constructor( props ) {
    super( props );
    this.bar = () => console.log('foo');
  }

  render() {
    return <p>Child</p>
  }
}
类父级扩展React.Component{
建造师(道具){
超级(道具);
this.childRef=React.createRef();
}
componentDidMount(){
this.childRef.current.bar()
}
render(){
返回(
);
}
}
子类扩展了React.Component{
建造师(道具){
超级(道具);
this.bar=()=>console.log('foo');
}
render(){
返回Child

} }

检查是否尝试了
Child.method()
?您不能。引起这个问题的用例是什么?@RobinZigmond我需要实现一个
元素,当它被单击时(通过将
this.bar
作为
onClick
传递),该元素将调用
this.bar
元素不能位于
中,因此按钮是
父项的子项,但与
子项不同?在这种情况下,将
bar
作为
Parent
的一种方法,并将其作为道具传递给
Child
,如果您在那里也需要它。您可以使用类似
destroy
的属性,在Child override
componentdiddupdate
中,并在设置
destroy
属性时调用
this.editor.destroy()