Ale*_*ang 72 javascript select input reactjs
例如:http://codepen.io/Enclave88/pen/YqNpog?edit = 1010
var InputBox = React.createClass({
render: function() {
return (
<input className="mainInput" value='Some something'></input>
)
}
});
Run Code Online (Sandbox Code Playgroud)
dsc*_*chu 139
Functional component:const handleFocus = (event) => event.target.select();
const Input = (props) => <input type="text" value="Some something" onFocus={handleFocus} />
Run Code Online (Sandbox Code Playgroud)
ES6 class component:class Input extends React.Component {
handleFocus = (event) => event.target.select();
render() {
return (
<input type="text" value="Some something" onFocus={this.handleFocus} />
);
}
}
Run Code Online (Sandbox Code Playgroud)
React.createClass:React.createClass({
handleFocus: function(event) {
event.target.select();
},
render: function() {
return (
<input type="text" value="Some something" onFocus={this.handleFocus} />
);
},
})
Run Code Online (Sandbox Code Playgroud)
Fac*_*ier 11
让我们根据@dschu 的答案添加最简单的:
...
<input type='text' value='Some something' onFocus={e => e.target.select()} />
...
Run Code Online (Sandbox Code Playgroud)
谢谢,我很感激。我是这样做的:
var input = self.refs.value.getDOMNode();
input.focus();
input.setSelectionRange(0, input.value.length);
Run Code Online (Sandbox Code Playgroud)
使用 useRefHook 的另一种方式功能组件:
const inputEl = useRef(null);
function handleFocus() {
inputEl.current.select();
}
<input
type="number"
value={quantity}
ref={inputEl}
onChange={e => setQuantityHandler(e.target.value)}
onFocus={handleFocus}
/>
Run Code Online (Sandbox Code Playgroud)
小智 5
var InputBox = React.createClass({
getInitialState(){
return {
text: ''
};
},
render: function () {
return (
<input
ref="input"
className="mainInput"
placeholder='Text'
value={this.state.text}
onChange={(e)=>{this.setState({text:e.target.value});}}
onFocus={()=>{this.refs.input.select()}}
/>
)
}
});
Run Code Online (Sandbox Code Playgroud)
你必须在输入上设置ref,在聚焦时你必须使用select().
| 归档时间: |
|
| 查看次数: |
38179 次 |
| 最近记录: |