我期待创建一个无状态组件,其输入可以由父元素验证.
在下面的示例中,我遇到了一个问题,即输入引用永远不会被分配给父的私有_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.
原文链接:https://www.f2er.com/react/301249.html无状态的想法是没有为它创建实例(状态).因此,您无法附加引用,因为没有附加引用的状态.
您最好的选择是传递组件更改时的回调,然后将该文本分配给父级的状态.
或者,您可以完全放弃无状态组件并使用普通的类组件.
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> ); }