在React js中将功能组件转换为类组件

时间:2020-03-11 12:47:21

标签: reactjs material-ui material-design react-state react-ref

在我的项目中,我使用类组件而不是功能组件,因为我在每个网站上都获得了所有功能组件。您能帮我将功能组件转换为类组件吗?并且请帮助我默认为多个链接选择所需的第一个值。

这是代码沙盒代码https://codesandbox.io/s/material-demo-dt504

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';

const useStyles = makeStyles(theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120,
  },
  selectEmpty: {
    marginTop: theme.spacing(2),
  },
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState('');

  const inputLabel = React.useRef(null);
  const [labelWidth, setLabelWidth] = React.useState(0);
  React.useEffect(() => {
    setLabelWidth(inputLabel.current.offsetWidth);
  }, []);

  const handleChange = event => {
    setAge(event.target.value);
  };

  return (
    <div>
     
      <FormControl variant="outlined" className={classes.formControl}>
        <InputLabel ref={inputLabel} id="demo-simple-select-outlined-label">
          Age
        </InputLabel>
        <Select
          labelId="demo-simple-select-outlined-label"
          id="demo-simple-select-outlined"
          value={age}
          onChange={handleChange}
          labelWidth={labelWidth}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    
    </div>
  );
}

2 个答案:

答案 0 :(得分:1)

希望这能为您完成工作

一些文章:https://www.digitalocean.com/community/tutorials/five-ways-to-convert-react-class-components-to-functional-components-with-react-hooks

Converting React function component to class component issue

编辑

要选择第一个值,请在代码中传递像这样的确切值
const [age,setAge] = React.useState(“ 10”);

import React from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';

export default class SimpleMenu extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      anchorEl: null
    };
  }

  handleClick = event => {
    this.setState({anchorEl: event.currentTarget});
  };

  handleClose = () => {
    this.setState({anchorEl: null});
  };

  render() {
    let { anchorEl } = this.state;
    return (
      <div>
        <Button
          aria-controls="simple-menu"
          aria-haspopup="true"
          onClick={this.handleClick}
        >
          Open Menu
        </Button>
        <Menu
          id="simple-menu"
          anchorEl={anchorEl}
          keepMounted
          open={Boolean(anchorEl)}
          onClose={this.handleClose}
        >
          <MenuItem onClick={this.handleClose}>Profile</MenuItem>
          <MenuItem onClick={this.handleClose}>My account</MenuItem>
          <MenuItem onClick={this.handleClose}>Logout</MenuItem>
        </Menu>
      </div>
    );
  }
}

答案 1 :(得分:1)

useState钩子:初始状态被赋予构造函数中的this.state,并使用this.setState合并成键值状态更新值对。

useEffect钩子:具有空的依赖项数组大致等效于componentDidMount生命周期函数,因此请将该逻辑移到那里。

useRef钩子:仅使用标准的反应引用。

useStyles挂钩:保留使用回调函数的主题,并使用withStyles HOC装饰器。

import React, { Component, createRef } from "react";
import { withStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
});

class SimpleSelect extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age: "",
      labelWidth: 0
    };

    this.inputLabel = createRef();
  }

  componentDidMount() {
    this.setState({ labelWidth: this.inputLabel.current.offsetWidth });
  }

  handleChange = event => this.setState({ age: event.target.value });

  render() {
    const { age, labelWidth } = this.state;
    const { classes } = this.props;
    return (
      <div>
        <FormControl variant="outlined" className={classes.formControl}>
          <InputLabel
            ref={this.inputLabel}
            id="demo-simple-select-outlined-label"
          >
            Age
          </InputLabel>
          <Select
            labelId="demo-simple-select-outlined-label"
            id="demo-simple-select-outlined"
            value={age}
            onChange={this.handleChange}
            labelWidth={labelWidth}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </div>
    );
  }
}

export default withStyles(useStyles)(SimpleSelect);

Edit Material demo