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 overridecomponentdiddupdate
中,并在设置destroy
属性时调用this.editor.destroy()
。