簡體   English   中英

在react中單擊錨標記后,將焦點設置在輸入元素上

[英]set focus on input element after clicking an anchor tag in react

我有兩個組成部分:

在我的父組件中,我有:

    //set focus object to false
    // include Child Component and React libraries
    const parent = React.createClass({
    getInitialState: function() {
      return {
        focus: false
      };
    },
      render() {
        return(
          <div>
            <Child focus={this.state.focus} />
            <a onClick={this._handleClick}>Click me</a>
          </div>
        );
      },

      _handleClick: function() {
        this.setState({focus: !this.state.focus});
      },
    };

在子組件中,我有一個輸入標簽:

 const child = React.createClass({
      render() {
        return(
          <div>
            <input type="text" ref="input" />
          </div>
        );
      },

  componentWillReceiveProps: function() {
    this.refs.input.focus();
  },
};

總而言之,我想在我的方法中做的是通過更改prop來調用componentWillReceiveProps來專注於輸入標簽。 但是現在這不起作用。 最終只關注錨標記。 任何我做錯事的想法嗎?

編輯:要進一步詳細說明我的問題,是一旦我單擊了定位標記,子組件中的input元素就不會被關注。 我如何才能使其專注於?

componentWillReceiveProps在子級的render方法之前執行。 因此, render可能會在獲得焦點之后立即破壞input元素。 您很可能只需將componentWillReceiveProps更改為componentDidUpdate ,就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM