聚焦时如何使用Reactjs选择输入中的所有文本?

IT技术 javascript select input reactjs
2021-05-07 00:07:40

例如:代码笔

var InputBox = React.createClass({
  render: function() {
    return (
      <input className="mainInput" value='Some something'></input>
    )
  }
});
4个回答

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} />
      );
    },
})

谢谢,我很感激。我是这样做的:

var input = self.refs.value.getDOMNode();
            input.focus();
            input.setSelectionRange(0, input.value.length);
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()。

使用 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}
/>