点击 <div> 聚焦 <input> (React)

IT技术 javascript html reactjs
2021-05-03 05:07:53

我知道如何用 jquery 做到这一点。但我坚持使用 React:每当用户单击 div 时,我将如何聚焦输入字段?

3个回答

您需要onClick在 div 上有一个事件,并在focus()您可以refs在react中访问的输入元素上调用该函数

class App extends React.Component {
  
  render() {
    return (
      <div>
          <div onClick={() => {this.myInp.focus()}}>Focus Input</div>
          <input type="text" ref={(ip) => this.myInp = ip} />
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

在上面的代码片段中ref={(ip) => this.myInp = ip}react-docs推荐的声明refs的回调方法

检查这个https://facebook.github.io/react/docs/refs-and-the-dom.html

通过ref你可以做任何类似 jquery 的事情。

试试这个:

var Hello = React.createClass({
    getInitialState: function() {
        return {
            value: 1,
            editMode: false
        };
    },
    edit: function() {
        this.setState({editMode: true});
    },
    handleChange: function(event) {
        this.setState({value: event.target.value});
    },
    focusInput(component) {
        if (component) {
            React.findDOMNode(component).focus(); 
        }
    },
    render: function() {
        if (true === this.state.editMode) {
            return (
                <input 
                  ref={this.focusInput} 
                  type="text" 
                  value={this.state.value} 
                  onChange={this.handleChange} />
            );
        }
        return (
            <div>The value is: <span>{this.state.value}</span> 
                <button onClick={this.edit}>
                    Edit
                </button>
            </div>
        );
    }
});

React.render(
    <Hello name="World" />, 
    document.getElementById('container')
);