将道具传递给使用包装纸的子组件

时间:2019-05-11 06:35:14

标签: reactjs react-router react-props react-wrapper

我是新来的人。

在我的应用中,我有一个路由器组件,并且正在使用render方法传递道具。子组件具有用于身份验证的包装器。

问题在于,当使用包装传递到组件时,它对道具没有可见性。抱歉,我是新来的,不知道在这种情况下如何将道具归结到子组件。

我创建了一些测试类来说明问题。一旦添加了包装器,我将无法访问道具,但是如果没有它,它就可以工作。

父母:

import React, { Component } from "react";
import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import MyComponent from "./mycomponent";

class MyTest extends Component {
  // Then we add our constructor which receives our props
  constructor(props) {
      super(props);
      // Next we establish our state
      this.state = {
          text: "Passing props to components"
      }
  }


  render() {
    return (
      <HashRouter>
      <div>
      <NavLink to="/rtest" replace>Route Test</NavLink>
      <Route path="/rtest" render={props => (<MyComponent {...props} text={this.state.text}/>)}/>
      </div>
      </HashRouter>
    )
  }

}

export default MyTest

孩子:

import React, { Component } from "react";
import AuthService from './auth/AuthService';
import withAuth from './auth/withAuth';

const Auth = new AuthService();


class MyComponent extends Component {
  constructor(props) {
      super(props);
  }


  componentWillMount() {
    console.log(this.props);
  }

  render() {
    return (
      <div>
        <h2>HELLO</h2>
      </div>
    );
  }
}

export default withAuth(MyComponent);

WithAuth:

import React, { Component } from 'react';
import AuthService from './AuthService';

export default function withAuth(AuthComponent) {
    const Auth = new AuthService('http://localhost:8000');
    return class AuthWrapped extends Component {
        constructor() {
            super();
            this.state = {
                user: null
            }
        }

        componentWillMount() {
            //alert(this.props);
            if (!Auth.loggedIn()) {
                this.props.history.replace('/login')
            }
            else {
                try {
                    const profile = Auth.getProfile()
                    this.setState({
                        user: profile
                    })
                }
                catch(err){
                    Auth.logout()
                    this.props.history.replace('/login')
                }
            }
        }

        render() {
            if (this.state.user) {
                return (
                    <AuthComponent history={this.props.history} user={this.state.user} />
                )
            }
            else {
                return null
            }
        }
    };
}

0 个答案:

没有答案