我有两个部分:
- 父组件
- 子组件
我试图从父级调用Child的方法,我尝试了这种方法,但没有得到结果:
类父级扩展组件{
render(){
返回(
<;儿童>;
<;button onClick={Child.getAlert()}>;单击<;/button>;
<;/Child>;
);
}
}
类子扩展组件{
getAlert(){
警报(“点击”);
}
render(){
返回(
<;h1 ref=“您好”您好<;/h1>;
);
}
}
有没有办法从父对象调用子对象的方法
注意:子组件和父组件位于两个不同的文件中
首先,让我表示,这通常不是英国人做事的方式。通常,您要做的是在道具中将功能传递给子级,并在事件中传递来自子级的通知(或者更好的是:dispatch)
但如果必须在子组件上公开命令式方法,则可以使用refs。请记住,这是一个逃生舱口,通常表明有更好的设计可用
以前,只有基于类的组件才支持引用。
随着React钩子的出现,情况不再如此
现代版使用挂钩(v16.8+)
const{forwardRef,useRef,useImperialiveHandle}=React;
//我们需要将组件包装在'forwardRef'中以获得
//访问使用'ref'属性指定的ref对象。
//此ref作为第二个参数传递给函数组件。
const Child=forwardRef((道具,ref)=>{
//组件实例将被扩展
//无论你从回调中返回什么
//作为第二个论点
使用命令式手柄(参考,()=>({
getAlert(){
警报(“从子项获取警报”);
}
}));
返回<;h1>;高<;/h1>;;
});
常量父项=()=>;{
//为了访问子组件实例,
//您需要将其分配给一个'ref',因此我们调用'useRef()'来获得一个
const childRef=useRef();
返回(
<;div>;
<;Child ref={childRef}/>;
<;button onClick={()=>;childRef.current.getAlert()}>;单击<;/button>;
<;/div>;
);
};
ReactDOM.render(
<;父项/>;,
document.getElementById('root'))
);
<;脚本src=”https://unpkg.com/[email protected]/umd/react.development.js“crossorigin></脚本>;
<;脚本src=”https://unpkg.com/[email protected]/umd/react dom.development.js“crossorigin></脚本>;
<;div id=“root”></部门>
useImperialiveHandle()的文档如下:
useImperialiveHandle自定义在使用ref时向父组件公开的实例值
使用类组件的旧API(>;[email protected])
const{Component}=React;
类父级扩展组件{
建造师(道具){
超级(道具);
this.child=React.createRef();
}
onClick=()=>{
this.child.current.getAlert();
};
render(){
返回(
<;div>;
<;Child ref={this.Child}/>;
<;button onClick={this.onClick}>;单击<;/button>;
<;/div>;
);
}
}
类子扩展组件{
getAlert(){
警报(“从子级获取警报”);
}
render(){
返回<;h1>;您好<;/h1>;;
}
}
ReactDOM.render(<;Parent/>;,document.getElementById('root'))
<;脚本src=”https://unpkg.com/[email protected]/umd/react.development.js“crossorigin></脚本>;
<;脚本src=”https://unpkg.com/[email protected]/umd/react dom.development.js“crossorigin></脚本>;
<;div id=“root”></部门>
回调引用API
回调样式引用是实现这一点的另一种方法,尽管在现代React中并不常见:
const{Component}=React;
const{render}=ReactDOM;
类父级扩展组件{
render(){
返回(
<;div>;
<;Child ref={instance=>;{this.Child=instance;}}/>;
<;button onClick={()=>;{this.child.getAlert();}}>;单击<;/button>;
<;/div>;
);
}
}
类子扩展组件{
getAlert(){
警报(“点击”);
}
render(){
返回(
<;h1>;您好<;/h1>;
);
}
}
渲染(
<;父项/>;,
document.getElementById('app')
);
<;脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js“></脚本>;
<;脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js“></脚本>;
<;div id=“应用程序”></部门>