2016-11-26 31 views
1

這可能是重複的,但是在與此標題相關的線程(我搜索的)中沒有任何一個有解決方案,而不是解釋爲什麼它是不可能的使用。ReactJs:如何在無狀態組件中使用refs

我必須使用一個組件,其中包含一個帶有ref的輸入文本元素。

let FormGroup = ({className, ref, value, maxLength}) => { 
    return <div className="form-group"> 
     <div className="form-group-inner"> 
      <input ref={ref} type="text" class={className} value={value} maxlength={maxLength}/> 
      <i className="form-group-helper"></i> 
     </div> 
    </div> 
} 

export default FormGroup 

當我重新使用它,

<FormGroup 
    className={'form-control form-control-sm'} 
    ref={'maxUserElement'} 
    value={'SMM-00012'} 
    maxLength={12} 
    onChange={this.handleFormControl.bind(this)} 
/> 

我不斷收到以下控制檯錯誤:

Stateless function components cannot have refs.

請幫我解決這個問題。

+0

這似乎已經在陣營內回購在長時間的討論已經:https://github.com/ Facebook的/反應/問題/ 4936 –

回答

1

你應該可以通過改變你的道具名稱來完成它。問題在於你在FormGroup上分配了ref,而不是真的把它傳下來。

<FormGroup 
    className={'form-control form-control-sm'} 
    inputRef={'maxUserElement'} 
    value={'SMM-00012'} 
    maxLength={12} 
    onChange={this.handleFormControl.bind(this)} 
/> 

... 

<input ref={inputRef} type="text" class={className} value={value} maxlength={maxLength}/> 

雖然目前還不清楚爲什麼你真的想這樣做,除非你手動尋找れ後來,否則你FormGroup分量仍然沒有對底層input任何直接訪問。

此外,this comment從提出了這個React GitHub issue給出了潛在的問題的一個很好的解釋:

a ref, which essentially, a backing instance, can only be returned from a stateful component or a DOM, but not a stateless component, because there is no instance created for a stateless component.

相關問題