【问题标题】:Ref current is always null when rendering my element for the first time?第一次渲染我的元素时,参考电流始终为空?
【发布时间】:2020-01-23 10:17:17
【问题描述】:

所以我想我的问题很简单,我希望当我单击一个元素时,我的输入获得焦点,所以这是我的组件上的方法和构造函数:

constructor(props) {
    super(props);
    this.textInput = React.createRef();
    this.state = {
      searchValue: ""
    };
  }
  activateSearchZone = action => {
    this.props.activateSearchZone(action);
    console.log(this.textInput);
    this.textInput.current.focus();

  };

  handleSearchZone = event => {
    let searchValue = event.target.value;
    this.props.searchForUsers(searchValue, { isSearching: true });
    setTimeout(() => {
      this.props.searchForUsers(searchValue, {
        isSearching: false,
        searchDone: true
      });
    }, 1000);
    this.setState({
      searchValue
    });
  };

这是我的组件:

   {this.props.searchList.activated && (
          <div className="search-bar__zone">
            <FontAwesomeIcon icon={faSearch} size="xs"></FontAwesomeIcon>
            <input
              placeholder="Search"
              onChange={event => this.handleSearchZone(event)}
              value={this.state.searchValue}
              type="text"
              ref={this.textInput}
            ></input>
            <FontAwesomeIcon
              icon={faTimesCircle}
              onClick={() => this.activateSearchZone(false)}
            ></FontAwesomeIcon>
          </div>
  )}

控制台日志显示当前值为null,我现在明白为什么了,我想是因为我的元素刚刚渲染,但我希望在单击时输入焦点。

我该怎么做?

非常感谢您的帮助。

【问题讨论】:

  • 你试过&lt;input type="text" autoFocus&gt; ??。我认为这会自动聚焦输入字段
  • @AkhilAravind 我以前不知道这个,我在文档中寻找它,这就是我真正需要的,它有效,谢谢,如果你想写,我可以将你的答案标记为正确作为答案。
  • 肯定会发布答案。

标签: reactjs


【解决方案1】:

您可以使用autofocus 属性聚焦input 元素。在反应中,它会像&lt;input type="text" autoFocus /&gt;,这样就可以了。

详细解释请参考链接https://davidwalsh.name/react-autofocus

【讨论】:

    【解决方案2】:

    这是因为react 不知道初始渲染时的ref。您需要使用forwardRef。它是 HOC 包装你的组件并告诉 react 有一些 ref。在它可用之前它不会渲染它。这是一个例子:

    const FancyButton = React.forwardRef((props, ref) => (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    ));
    

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2019-10-06
      • 2021-06-04
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多