我对autoFocus有个问题。它对我不起作用,但使用它:
<input onChange={this.handleName} value={this.state.name} placeholder="Name..." type="text" autoFocus />发布于 2018-03-24 16:10:39
很可能是你正在做的其他事情导致它失败。在这个简单的示例中,它工作得很好:
const App = React.createClass({
render() {
return (
<input
placeholder = "Name..."
type = "text"
autoFocus
/ >
);
}
});
ReactDOM.render( <
App / > ,
document.getElementById('root')
);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
发布于 2020-11-29 09:46:53
这些对我来说都不起作用:
<input type="text" autoFocus .../>
<input type="text" autoFocus={true} .../>
<input type="text" autoFocus="true" .../>
<input type="text" autoFocus="autofocus" .../>…即使在每种情况下,web检查器都显示呈现了<input type="text" autofocus .../>


也许是因为this phenomenon,我不确定:
如果您将React组件呈现为分离的元素,React将过早地调用
focus()。当您的React树被添加到DOM中时,这将导致input不聚焦。
这个为我做了工作:
import React, { useRef, useEffect } from "react";
export default function SignIn() {
const inputElement = useRef(null);
useEffect(() => {
if (inputElement.current) {
inputElement.current.focus();
}
}, []);
return (
<div>
<form action="...">
<input
ref={inputElement} // yes, this is working in Chrome on Mac
type="text" // allows username also; type 'email' woud insist on '@' sign
name="email"
placeholder="Email address"
autoComplete="email"
required
...
/>
</form>
</div>
);
}这是Daniel Johnson的第二个策略

发布于 2020-10-14 09:23:00
我有两个应用了autoFocus的输入,一个有效,另一个无效,它们都是reactstrap输入域:
import { Button, Input } from 'reactstrap';我发现其中一个只有一个类型,没有名称,这就是工作的那个。因此,我将另一个更改为相同的,它开始工作:
<Input
autoFocus="autofocus"
id="code"
type="text"
value={props.codeValue}
onChange={props.onCodeChange}
onKeyPress={event => {
if (event.key === 'Enter') {
confirmCode();
}
}}
/>https://stackoverflow.com/questions/49462561
复制相似问题