reactjs - 如何在 React 中附加到无状态组件的引用?

标签 reactjs typescript jsx

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

在下面的示例中,我遇到了一个问题,即输入 ref 从未分配给父级的私有(private) _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>
);

最佳答案

您可以使用自 v16.7.0-alpha 以来可用的useRef 钩子(Hook)。

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

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

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 documentation

关于reactjs - 如何在 React 中附加到无状态组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41048546/

相关文章:

javascript - 为什么嵌套 JSX 需要大括号,即使没有它也能工作

javascript - React js中default.a.map不是函数错误

reactjs - 如何使用 useLazyQuery() 在每次点击时执行查询

javascript - 如何计算列表中当前的滚动位置?

typescript - tsconfig 和环境声明中的项目引用

javascript - 在 JSX 中使用不同的 View 渲染数组

javascript - GatsbyJS - 构建显示错误窗口未定义 (AOS)

angular - 沿库导出服务 stub 时的循环依赖

typescript - Vue + Typescript 网页在 GAS sidemenu 模板中不可见

javascript - react 组件水平渲染而不是垂直渲染