簡體   English   中英

從另一個組件調用引用(?)

[英]Calling a ref from another component (?)

我正在聊天應用程序中使用React。 我需要每當您單擊聊天框時,應將輸入消息的輸入重點放在輸入框上。

我的問題是,位於主要組件中的聊天框與輸入消息的輸入所在的組件是分開的。

看, 主要組成部分

class ChatView extends React.Component {

  constructor (props) {
    super(props);
    this._inputFocus = this._inputFocus.bind(this);
  }

  _inputFocus () {
    let input = React.findDOMNode(this.refs.SHOULDFOCUS-HERE);
    input.focus();
  }
  render () {

    if (this.props.mode === 'player') {
      dealerPlayerMessages = <ul ref="messages">{messages}</ul>;

      // CHAT FORM IS THE COMPONENT CONTAINING THE INPUT
      chatForm = <ChatForm onAddMessage={this.addMessage} />;

      chatBox = <div>{dealerPlayerMessages}{chatForm}</div>
    }

    return <div className="dealer-player-box" onClick={this._inputFocus} >
      {chatBox}
    </div>;
  }
}

因此,如您所見,當您單擊類名稱為this._inputFocus dealer-player-box的div時,將調用函數this._inputFocus

但是輸入消息文本的輸入位於組件ChatForm

class ChatForm extends React.Component {

  constructor (props) {
    super(props);
  }

  render () {
    return (<div className="chat-form">

      // THIS IS THE INPUT I NEED TO FOCUS ON
      <input className="input-form"
        placeholder="Your message..."
        ref="SHOULDFOCUS-HERE"
        autofocus="true" />

    </div>);
  }
}

因此,從主要組件開始,我應該怎么做才能專注於該輸入,因為在另一個組件中?

向您的ChatForm添加一個引用:

<ChatForm ref="chatForm" onAddMessage={this.addMessage} />;

在您的ChatForm將輸入ref更改為有意義的內容:

<input className="input-form"
        placeholder="Your message..."
        ref="chatInput"
        autofocus="true" />

在您的ChatForm組件中添加一個方法,該方法着重於:

focusInput() {
  this.refs.chatInput.focus();
}

在您的ChatView組件中,修改_inputFocus方法:

_inputFocus() {
  this.refs.chatForm.focusInput();
}

請注意,如果您使用的是過時版本的react(<0.14),則使用ref可能會有所不同。

暫無
暫無

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

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