例如:codepen
var InputBox = React.createClass({
render: function() {
return (
<input className="mainInput" value='Some something'></input>
)
}
});
例如:codepen
var InputBox = React.createClass({
render: function() {
return (
<input className="mainInput" value='Some something'></input>
)
}
});
Answers:
Functional component
:const handleFocus = (event) => event.target.select();
const Input = (props) => <input type="text" value="Some something" onFocus={handleFocus} />
ES6 class component
:class Input extends React.Component {
handleFocus = (event) => event.target.select();
render() {
return (
<input type="text" value="Some something" onFocus={this.handleFocus} />
);
}
}
React.createClass
:React.createClass({
handleFocus: function(event) {
event.target.select();
},
render: function() {
return (
<input type="text" value="Some something" onFocus={this.handleFocus} />
);
},
})
<input type='text' value='Some something' onFocus={e => e.target.select()} />
disabled
使它适用于文本框?jsfiddle.net/69z2wepo/317733
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()}}
/>
)
}
});
您必须在输入上设置ref,并且在聚焦时必须使用select()。
谢谢,我很感激。我是这样做的:
var input = self.refs.value.getDOMNode();
input.focus();
input.setSelectionRange(0, input.value.length);
在我的情况下,我想从输入出现在模态之后的开头选择文本:
componentDidMount: function() {
this.refs.copy.select();
},
<input ref='copy'
var React = require('react');
var Select = React.createClass({
handleFocus: function(event) {
event.target.select()
},
render: function() {
<input type="text" onFocus={this.handleFocus} value={'all of this stuff'} />
}
});
module.exports = Select;
自动选择输入中所有内容的反应类别。输入标签上的onFocus属性将调用一个函数。OnFocus函数具有一个自动生成的称为事件的参数。就像上面显示的一样,event.target.select()将设置输入标签的所有内容。
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}
/>