html - 无论如何要在 React 中的页面加载上进行输入自动对焦
问题描述
我有一个 SPA,当页面加载时,我的所有组件都已经呈现在屏幕上。我将特定输入设置为自动对焦,屏幕会自动拍摄到输入所在的组件,而不是停留在页面顶部。有什么方法可以阻止此功能但保持输入自动或永久集中?
解决方案
我用scrollTo
,希望对你有帮助。
焦点在最后一个输入
class ScrollToTop extends React.Component {
focus = () => {
window.scrollTo(0, 0)
}
render() {
return ( <
div >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text' / >
<
input type = 'text'
onFocus = {
this.focus
}
autoFocus / >
<
/div>
);
}
}
ReactDOM.render( < ScrollToTop / > ,
document.getElementById("root")
);
div {
display: flex;
flex-direction: column;
}
div input {
outline: none !important;
line-height: 32px;
margin-bottom: 5px;
border-radius: 5px;
border: solid 1px #999;
width: 50%;
}
div input:focus {
outline: none !important;
border: 1px solid #00b1ff;
box-shadow: 0 0 10px #719ECE;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
推荐阅读
- swiftui - SwiftUI 应用程序显示领域变化但不是新对象
- php - 如何在laravel中对多个withcount()列求和和排序
- javascript - 使用 reduce 过滤数组
- python-3.x - 使用python从html获取javascript变量和数据
- symfony - 在共享 2 个环境的机器上运行 Symfony 3.2 项目中的作曲家安装
- python - 在一个单元格中转换具有多个值的数据框
- c# - 在构造函数中填充列表
- xslt - 使用 XSLT 1.0 提取没有不必要名称空间的 XSLT 标记
- python - 用漂亮的汤刮网页
- c# - 按下回车键时转到下一个文本框