[英]React input defaultValue focus and select
我有一个带有输入元素的组件,我使用defaultValue设置初始值。 我想关注该元素并首先选择整个值,但是似乎在调用componentDidMount时未设置默认值。
你有什么建议吗?
我使用window.setTimeout但我想在我的react-components中避免这种情况:
public componentDidMount(): void {
if (this.props.focus) {
let tInput: HTMLInputElement = ReactDOM.findDOMNode(this).getElementsByTagName("input").item(0);
if (tInput) {
tInput.focus();
// FixMe: defaultValue is set too late by react so i cant set selection instantly
if (this.props.defaultValue) {
window.setTimeout(
() => {tInput.setSelectionRange(0, this.props.defaultValue.length); },
100
);
}
}
}
}
对我来说效果很好:
class MyComponent extends React.Component {
componentDidMount () {
const { myInput } = this.refs
myInput.focus()
myInput.select()
}
render () {
return (
<input type='text' defaultValue='Foobar' ref='myInput' />
)
}
}
除了render / renderToString之外,我不会使用任何reactDOM方法。 这些api是“逃生舱口”,不建议使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.