How can I attach to a stateless component's ref in React?

后端 未结 5 2240
悲哀的现实
悲哀的现实 2020-12-08 03:48

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

In my example below, I am running into a pro

5条回答
  •  悲哀的现实
    2020-12-08 04:15

    The value of your TextInput is nothing more than a state of your component. So instead of fetching the current value with a reference (bad idea in general, as far as I know) you could fetch the current state.

    In a reduced version (without typing):

    class Form extends React.Component {
      constructor() {
        this.state = { _emailAddress: '' };
    
        this.updateEmailAddress = this.updateEmailAddress.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      updateEmailAddress(e) {
        this.setState({ _emailAddress: e.target.value });
      }
    
      handleSubmit() {
        console.log(this.state._emailAddress);
      }
    
      render() {
        return (
          
    ); } }

提交回复
热议问题