You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何通过refs给input设置焦点?条件渲染后调用focus报错如何解决?

错误原因

你调用的setIsTouched是React的异步状态更新方法,执行后不会立刻触发组件重渲染,也不会立刻挂载<ViewModule />组件。此时你直接调用textInput.current.focus(),绑定在<ViewModule />内部input上的ref还没完成赋值,current属性还是初始值null,就会抛出该类型错误。

解决方案

把聚焦逻辑放到useEffect钩子中,监听isTouched状态的变化,等状态更新、组件重渲染完成、<ViewModule />挂载完毕后再执行聚焦操作,只需修改Sales组件代码即可:

const Sales = () => {
    const [isTouched, setIsTouched] = useState(false);
    const textInput = useRef(null);


    function handleInput() {
        setIsTouched(true);
        // 移除此处的focus调用
    }

    // 新增useEffect监听isTouched变化
    useEffect(() => {
        // 增加判断条件避免边界报错
        if (isTouched && textInput.current) {
            textInput.current.focus();
        }
    }, [isTouched])

    const readyBlock = isTouched ? <ViewModule textInput={textInput}/> : null;
    return (
        <main className="sales-page">
            <div className="main__title">
                <h2 className="main__heading">Bonuses</h2>
            </div>
            <div className="content-container">
                <UploadForm>
                    <FileUploadInput 
                        handleChange={handleInput}
                        placeholder="Header"/>
                    <FileUploadTextArea placeholder="Descr"/>
                </UploadForm>
            </div>
            <div className="ready-container ">
                {readyBlock}
            </div>
        </main>
    )
}

补充说明

如果你需要保持聚焦的是用户点击的原有input,而非新生成区块的input,需要给原有input也单独绑定ref,再调整聚焦逻辑即可,当前你的ref是绑定在新生成的input上的,和你描述的需求存在出入,可以根据实际场景调整。

内容的提问来源于stack exchange,提问作者Wells

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:21:03