简体   繁体   中英

ReactJs: How to use refs in stateless component

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.

You should be able to do it just by changing the name of your prop. The issue is that your assigning a ref on FormGroup rather than actually passing it down.

<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}/>

Though it's not clear why you'd really want to do this unless you are manually finding the DOMnode later, since otherwise your FormGroup component still doesn't have any direct access to the underlying input .

Also, this comment from the React GitHub issue raised about this gives a good explanation of the underlying 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM