reactjs – 如何在React中附加无状态组件的ref?

我期待创建一个无状态组件,其输入可以由父元素验证.

在下面的示例中,我遇到了一个问题,即输入引用永远不会被分配给父的私有_emailAddress属性.

调用handleSubmit时,this._emailAddress未定义.有什么我想念的,还是有更好的方法来做到这一点?

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>
);
您无法在无状态组件(包括refs)上访问类似React的方法(如componentDidMount,componentwillReceiveProps等). Checkout this discussion on GH为完整的convo.

无状态的想法是没有为它创建实例(状态).因此,您无法附加引用,因为没有附加引用的状态.

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

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

From the docs…

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 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...