转换为类组件?

时间:2020-09-26 10:37:35

标签: javascript reactjs

当我将其转换为类组件时,正在定义

props。所以我们应该如何编写这是类组件

const Admin = props => {
      console.log(props);
      const username  = props.location.username;
        
      return (
        <div>
          <NavLink to="/" activeClassName="active">
            LOGOUT
          </NavLink>
          <br/>
          <br/>
         <Button>hello</Button>
            <h2> Username </h2> {username}
            <h1>child component-MILAN</h1>
          </div>
      );

2 个答案:

答案 0 :(得分:1)

类组件

import React, { Component } from 'react';

export default class Admin extends Component {
  render() {
    const username = this.props.location.username;
    return (
      <div>
        <NavLink to="/" activeClassName="active">
          LOGOUT
        </NavLink>
        <br />
        <br />
        <Button>hello</Button>
        <h2> Username </h2> {this.username}
        <h1>child component-MILAN</h1>
      </div>
    );
  }
}

答案 1 :(得分:-2)

如果要继续使用功能组件,

import React from 'react';

// YOUR OTHER IMPORT GOES HERE

const Admin = ({ props }) => {
    console.log(props);
    const { username } = props.location;
    return (
        <div>
            <NavLink to="/" activeClassName="active">LOGOUT</NavLink>
            <br /><br />
            <Button>hello</Button>
            <h2> Username </h2> {username}
            <h1>child component-MILAN</h1>
        </div>
    )
}

类组件:

import React from 'react';
import { withRouter } from 'react-router';

// YOUR OTHER IMPORT GOES HERE

class Admin extends React.Component {
    componentDidMount() {
        console.log(this.props);
        const { username } = this.props.location;
    }
    render() {
        const { } = this.props.location.state
        return (
            <div>
                <NavLink to="/" activeClassName="active"> LOGOUT</NavLink>
                <br /><br />
                <Button>hello</Button>
                <h2> Username </h2> {username}
                <h1>child component-MILAN</h1>
            </div>
        )
    }
}

export default withRouter(Admin);