ReactJs: How to use refs in stateless component

时间:2016-11-26 18:30:22

标签: javascript reactjs redux

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.

1 个答案:

答案 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 commentReact GitHub issue对此提出了一个很好的解释:

  

一个ref,它本质上是一个支持实例,只能返回   来自有状​​态组件或DOM,但不是无状态组件,   因为没有为无状态组件创建实例。