【问题标题】:Convert Uncontrolled Components from : Class extends to Functional Components?将不受控制的组件从:类扩展为功能组件?
【发布时间】:2021-10-04 10:44:10
【问题描述】:

我在将 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;

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

【问题讨论】:

  • 你在类组件中没有state,你需要吗?

标签: javascript reactjs react-functional-component react-class-based-component


【解决方案1】:

可以这样做:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 2021-08-23
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2016-10-30
    相关资源
    最近更新 更多