0

我在类组件中的代码

我仍然是学习 React 的新手,我很难将类组件转换为功能组件。

  class App extends React.Component {
  handleChange = (e) => {
    const { name, value } = e.target
    this.setState({
      [name]: value
    })
  }
  configureCaptcha = () => {
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {

        this.onSignInSubmit();
        console.log("Recaptca varified")
      },
      defaultCountry: "IN"
    });
  }
  onSignInSubmit = (e) => {
    e.preventDefault()
    this.configureCaptcha()
    const phoneNumber = "+91" + this.state.mobile
    console.log(phoneNumber)
    const appVerifier = window.recaptchaVerifier;
    firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
      .then((confirmationResult) => {
        window.confirmationResult = confirmationResult;
        console.log("OTP has been sent")
      }).catch((error) => {
        console.log("SMS not sent")
      });
  }

  render() {
    .....
    )
  }
}
export default App;

我在 Component 类中的输出

在此处输入图像描述

如何在 reactjs 中使用钩子将类组件转换为函数组件

4

1 回答 1

1

代码看起来像这样的新语法。但我建议将name和的值mobile严格分开存储,useStates以使代码更清晰:

const App = () => {
  const [values, setValues] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;

    setValues({ [name]: value, ...values });
  };

  const configureCaptcha = () => {
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
      "sign-in-button",
      {
        size: "invisible",
        callback: (response) => {
          onSignInSubmit();
          console.log("Recaptca varified");
        },
        defaultCountry: "IN",
      }
    );
  };

  const onSignInSubmit = (e) => {
    e.preventDefault();
    configureCaptcha();
    const phoneNumber = "+91" + values.mobile;
    console.log(phoneNumber);
    const appVerifier = window.recaptchaVerifier;
    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber, appVerifier)
      .then((confirmationResult) => {
        window.confirmationResult = confirmationResult;
        console.log("OTP has been sent");
      })
      .catch((error) => {
        console.log("SMS not sent");
      });
  };

  return <div></div>;
};

export default App;

于 2021-06-29T08:21:40.927 回答