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

新手上路,请多包涵

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

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

当调用 handleSubmit 时, this._emailAddressundefined 。有什么我想念的,还是有更好的方法来做到这一点?

 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>
);

原文由 drewwyatt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 601
2 个回答

编辑:您现在可以使用 React Hooks。请参阅安特古林的答案。

您不能在无状态组件(包括 refs )上访问类似 React 的方法(如 componentDidMountcomponentWillReceiveProps 等)。 查看关于 GH 的此讨论以 获取完整的 convo。

无状态的想法是没有为它创建实例(状态)。因此,您不能附加 ref ,因为没有状态可以附加参考。

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

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

从文档…

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

 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>
  );
}

原文由 BradByte 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 useRef 挂钩,该挂钩自 v16.7.0-alpha 起可用。

编辑:16.8.0 发布开始,我们鼓励您在生产中使用 Hooks!

挂钩使您能够维护状态并处理功能组件中的副作用。

 function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

Hooks API 文档 中阅读更多内容

原文由 Ante Gulin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进