如何在React中附加到无状态组件的ref? [英] How can I attach to a stateless component's ref in React?

查看:183
本文介绍了如何在React中附加到无状态组件的ref?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个无状态组件,其input元素可以由父组件验证.

I am looking to create a stateless component who's input element can be validated by the parent component.

在下面的示例中,我遇到了一个问题,其中输入ref从未分配给父级的私有_emailAddress属性.

In my example below, I am running into a problem where the input ref is never being assigned to the parent's private _emailAddress property.

调用handleSubmit时,this._emailAddressundefined.是否有我想念的东西,或者有更好的方法来做到这一点?

When handleSubmit is called, this._emailAddress is undefined. Is there something I'm missing, or is there a better way to do this?

interface FormTestState {
    errors: string;
}

class FormTest extends React.Component<void, FormTestState> {
    componentWillMount() {
        this.setState({ errors: '' });
    }

    render(): JSX.Element {
        return (
            <main role='main' className='about_us'>             
                <form onSubmit={this._handleSubmit.bind(this)}>
                    <TextInput 
                        label='email'
                        inputName='txtInput'
                        ariaLabel='email'
                        validation={this.state.errors}
                        ref={r => this._emailAddress = r}
                    />

                    <button type='submit'>submit</button>
                </form>
            </main>
        );
    }

    private _emailAddress: HTMLInputElement;

    private _handleSubmit(event: Event): void {
        event.preventDefault();
        // this._emailAddress is undefined
        if (!Validators.isEmail(this._emailAddress.value)) {
            this.setState({ errors: 'Please enter an email address.' });
        } else {
            this.setState({ errors: 'All Good.' });
        }
    }
}

const TextInput = ({ label, inputName, ariaLabel, validation, ref }: { label: string; inputName: string; ariaLabel: string; validation?: string; ref: (ref: HTMLInputElement) => void }) => (
    <div>
        <label htmlFor='txt_register_first_name'>
            { label }
        </label>

        <input type='text' id={inputName} name={inputName} className='input ' aria-label={ariaLabel} ref={ref} />

        <div className='input_validation'>
            <span>{validation}</span>
        </div>
    </div>
);

推荐答案

您现在可以使用React Hooks.请参阅Ante Gulin的答案.

您不能在包括refs在内的无状态组件上访问类似React的方法(例如componentDidMountcomponentWillReceiveProps等). 在GH上查看此讨论以了解完整的内容.

You can't access React like methods (like componentDidMount, componentWillReceiveProps, etc) on stateless components, including refs. Checkout this discussion on GH for the full convo.

无状态的想法是没有为其创建一个实例(状态).因此,您无法附加ref,因为没有状态可以将引用附加到该位置.

The idea of stateless is that there isn't an instance created for it (state). As such, you can't attach a ref, since there's no state to attach the ref to.

您最好的选择是在组件更改时传递回调,然后将该文本分配给父对象的状态.

Your best bet would be to pass in a callback for when the component changes and then assign that text to the parent's state.

或者,您可以完全放弃无状态组件,而使用普通的类组件.

Or, you can forego the stateless component altogether and use an normal class component.

来自文档. ..

您不能在功能组件上使用ref属性,因为它们没有实例.但是,您可以在功能组件的render函数中使用ref属性.

You may not use the ref attribute on functional components because they don't have instances. You can, however, use the ref attribute inside the render function of a functional component.

function CustomTextInput(props) {
  // textInput must be declared here so the ref callback can refer to it
  let textInput = null;

  function handleClick() {
    textInput.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={(input) => { textInput = input; }} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );  
}

这篇关于如何在React中附加到无状态组件的ref?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆