如何编写自动选择表单域的React组件?
例如,在jQuery中,您可以使用select()自动选择表单域
<html lang="en">
<head>
<meta charset="utf-8">
<title>select demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input type="text" name="foo" value="Some text">
<script>
$("input").select();
</script>
</body>
</html>如何使用React实现类似的效果?
对于某些上下文,我正在尝试编写一个可编辑的表单元素,用户可以通过单击它来对其进行编辑,类似于下面的代码:https://gist.github.com/hanneshapke/4a12dd414a193d5406ea。但是,当表单域进入编辑模式时,此gist并不会自动选择它,用户必须再次单击才能更改文本。
发布于 2017-08-05 10:31:11
不要直接操作DOM!
componentDidMount() {
this.refs.myFoo.select();
}
render() {
return (
<div>
<input ref="myFoo" type="text" value="123"/>
</div>
);
}发布于 2017-08-05 10:07:12
为了在您链接的代码片段的上下文中回答您的问题,我将使用ref和setSelectionRange的组合:
handleEdit (e) {
this.textInput.setSelectionRange(0, this.textInput.value.length)
return (e) => this.setState({
editing: !this.state.editing
});
}
render() {
//...
// setting the ref on render...
<input
type="text"
ref={(input) => { this.textInput = input; }}
//...
/>
}https://stackoverflow.com/questions/45517427
复制相似问题