小编daw*_*awg的帖子

如何以编程方式在 React 中聚焦按钮?

自动对焦对我不起作用,因为我需要它(button2)在单击button1时聚焦,而不是在元素加载时聚焦。这就是我的代码的样子:

const MyComponent = props =>{

    return(<div>
                <button id='button1'>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用 ref 但它似乎不适用于按钮,仅适用于文本框等;当我用 an 替换 button2 时,<input>它工作正常:

const MyComponent = props =>{
    const btnRef = useRef()
    const handleClick = ()=>{
        btnRef.current.focus()
    }
    return(<div>
                <button id='button1' onClick={handleClick}>Button1</button>
                <button id='button2'>Button2</button>
           </div>);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让这种参考方法发挥作用?或者有什么方法可以让按钮以编程方式聚焦?

focus reactjs react-hooks

5
推荐指数
1
解决办法
8261
查看次数

Jest + React:IntersectionObserver 模拟不起作用?

在我的 component.test.js 中,我尝试通过执行以下操作来模拟 IntersectionObserver:

const mock = ()=>({
    observe: jest.fn(),
    disconnect: jest.fn()
});
window.IntersectionObserver = jest.fn().mockImplementation(mock);


describe("Component", ()=>{
    it("test 1", ()=>{
        render(<Component/>);
        ...
    }
});
Run Code Online (Sandbox Code Playgroud)

我的 component.js 看起来像这样(它执行无限分页操作):

//ref to last item loaded >> load more items once it enters view
const observer = useRef();
const lastEntryRef = useCallback((node)=>{
        ...
        observer.current.disconnect(); //ERROR LINE
    }
    ...
);
Run Code Online (Sandbox Code Playgroud)

然而,当我运行测试时,我得到TypeError: observer.current.disconnect is not a function;如果它运行的话也是如此observer.current.observe()。我尝试在 component.test.js 本身的 it() 块内测试它,方法是实例化 IntersectionObserver,然后调用这些方法,当我重新运行测试时,会显示相同的消息,因此错误看起来与 IntersectionObserver 的设置方式无关在组件.js 中。我没有正确嘲笑 IntersectionObserver 吗?如果是这样,我该如何修复它?

javascript unit-testing reactjs jestjs intersection-observer

4
推荐指数
1
解决办法
5671
查看次数