How to select all text in input with Reactjs, when

2019-02-01 03:36发布

For example: http://codepen.io/Enclave88/pen/YqNpog?editors=1010

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

5条回答
姐就是有狂的资本
2楼-- · 2019-02-01 04:16

In my case I wanted to select the text from the beginning after the input appeared in the modal:

componentDidMount: function() {
    this.refs.copy.select();
},

<input ref='copy'
查看更多
Melony?
3楼-- · 2019-02-01 04:20
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()}}
      />
    )
  }
});

You have to set ref on the input and when focused you have to use select().

查看更多
混吃等死
4楼-- · 2019-02-01 04:21
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;

Auto select all content in a input for a react class. The onFocus attribute on a input tag will call a function. OnFocus function has a parameter called event generated automatically. Like show above event.target.select() will set all the content of a input tag.

查看更多
聊天终结者
5楼-- · 2019-02-01 04:34

Thanks, I appreciate it. I did it so:

var input = self.refs.value.getDOMNode();
            input.focus();
            input.setSelectionRange(0, input.value.length);
查看更多
劫难
6楼-- · 2019-02-01 04:36

Class component:

class Input extends React.Component {
    handleFocus = (event) => event.target.select();

    render() {
        return (
            <input type="text" value="Some something" onFocus={this.handleFocus} />
        );
    }
}

Functional component:

const handleFocus = (event) => event.target.select();
const Input = (props) => <input type="text" value="Some something" onFocus={handleFocus} />

React.createClass:

handleFocus: function(event) {
  event.target.select();
},

render: function() {
  return (
    <input type="text" value="Some something" onFocus={this.handleFocus} />
  );
},
查看更多
登录 后发表回答