This could be a duplicate, but in none of the thread(which I searched) which is related to this heading have had the solution rather than having the explanation of why it's not possible to use.
I have to use a component which contains an input text element with a 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
When I reuse it,
<FormGroup
className={'form-control form-control-sm'}
ref={'maxUserElement'}
value={'SMM-00012'}
maxLength={12}
onChange={this.handleFormControl.bind(this)}
/>
I'm keep getting the following console error:
Stateless function components cannot have refs.
Kindly help me fix this issue.
答案 0 :(得分:2)
您应该只需更改道具的名称即可。问题是您在ref
上分配FormGroup
而不是实际传递它。
<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}/>
虽然不清楚为什么你真的想要这样做,除非你以后手动找到DOMnode,否则你的FormGroup
组件仍然没有对基础input
的任何直接访问权限
此外,来自this comment的React GitHub issue对此提出了一个很好的解释:
一个ref,它本质上是一个支持实例,只能返回 来自有状态组件或DOM,但不是无状态组件, 因为没有为无状态组件创建实例。