如何使用 Reactjs 在聚焦时选择输入中的所有文本? Functional component: ES6 class component: React.createClass:

2022-08-30 04:49:28

例如:密码笔

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

答案 1

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

答案 2

另一种方式功能组件与使用RefHook:

const inputEl = useRef(null);

function handleFocus() {
  inputEl.current.select();
}

<input
  type="number"
  value={quantity}
  ref={inputEl}
  onChange={e => setQuantityHandler(e.target.value)}
  onFocus={handleFocus}
/>