1

我在将Uncontrolled Components类组件转换为功能组件时遇到了麻烦......

类组件:

import React from 'react';

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    console.log('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
export default NameForm;

我想转换成功能组件。像这样的东西:

import React,{useState,useEffect} from 'react';

function App() {

const[inputText,setinputText] = useState();
//Rest of codes here::

return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
}
export default App;

我真的不知道如何转换构造函数。任何人请帮助我。

4

1 回答 1

2

可以这样做:

import React from "react";

const NameForm = () => {
  const inputRef = React.useRef();

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("A name was submitted: " + inputRef.current.value);        
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
};

export default NameForm;
于 2021-07-28T17:13:39.890 回答