javascript - 当它们在同一页面中时,如何使用 Hook(仅限 ForwardRef 概念)在子组件中调用父方法
问题描述
场景 1:工作正常
这是父组件
import React, { Children } from 'react'
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const buttonRef = React.useRef({ focusHandler: () => alert("hi") });
return (
<div>
<ChildComponent ref={buttonRef} />
</div>
);
};
export default ParentComponent;
这是使用前向引用的子组件。
import React from 'react'
const ChildComponent = React.forwardRef((props, ref) => {
return (
<div>
<button onClick={ref.current.focusHandler}>Focus Input</button>
</div>
);
});
export default ChildComponent;
场景 2:这里需要帮助
现在,如果 ParentComponent 没有 ChildComponent 并且我希望在主页中像这样调用 ChildComponent 怎么办:
MainPage.js:
import React from 'react'
import ParentComponentScenario2 from './ParentComponentScenario2';
import ChildComponentScenario2 from './ChildComponentScenario2';
const MainPage = () => {
return (
<div>
<ParentComponentScenario2>
<ChildComponentScenario2 />
</ParentComponentScenario2>
</div>
)
}
export default MainPage;
父组件场景 2:
import React, { Children } from 'react'
const ParentComponentScenario2 = () => {
const buttonRef = React.useRef({ focusHandler: () => alert("hi") });
return (
<div>
{props.children};
</div>
);
};
export default ParentComponentScenario2;
查询,我现在如何在 ChildComponent 中传递该方法,因为 <ChildComponent ref={buttonRef} />
现在在页面上是不可能的。
ChildComponentScenario2:
import React from 'react'
//How to implement onClick, props.focusHandler doesn't seem to work for some reason either.
const ChildComponentScenario2 = () => {
return (
<div>
<button onClick={props.focusHandler}>Focus Input</button>
</div>
)
}
export default ChildComponentScenario2;
解决方案
您需要使用React.Children
API 和“注入”属性React.cloneElement
:
const ParentComponent = ({ children }) => {
const buttonRef = React.useRef({ focusHandler: () => console.log("ref") });
const focusHandler = () => console.log("callback");
return (
<div>
{React.Children.map(children, child =>
React.cloneElement(child, { ref: buttonRef, focusHandler })
)}
</div>
);
};
const ChildComponent = React.forwardRef(({ focusHandler }, ref) => {
return (
<div>
<button onClick={ref?.current.focusHandler}>Ref</button>
<button onClick={focusHandler}>Callback</button>
</div>
);
});
推荐阅读
- c# - 如何翻译 NavigationView 菜单按钮?
- ruby-on-rails - 在视图中输入 will_pagenate 方法时收到错误数量的参数(给定 0,预期为 1)
- java - 安卓。向 Google Sheet 脚本发送 POST 请求
- tableau-api - 从计算中排除一堆值
- r - 在 r 中使用 ifelse 语句和 forloops 创建新变量
- javascript - 如何结合 Phaser 3 重力和阻力?
- python - Python中的Eig给出不同的特征值?
- arm - 如何使用 qemu 启动 U-boot / Uimage
- python - Pyti rsi 产生负数
- javascript - 无法使用量角器将焦点切换到 Safari 浏览器中的子窗口