React.js render 方法中的 props 从哪里获取

where do we get the props in render method in React.js

我已经将组件传递给子元素,我感到困惑的一件事是渲染方法获取 props 作为参数,然后我们将它们作为道具传递给其他 元素。我们在哪里以及如何在 render 方法的参数中获取这些道具。检查代码,特别是其中使用的渲染方法和道具谢谢

代码如下:

return (
    <div>
      <Route
        {...rest}
        render={(props) =>
          localStorage.getItem("authToken") ? (
            <Component {...props} />
          ) : (
            <Redirect to="/" />
          )
        }
      />
    </div>

这是来自父元素的代码

 <Privateroute exact path="/signup"   component={Register} />

这是工作示例:

Privateroute.js分量

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const Privateroute = ({component: Component, ...rest}) => {
    return (
        <Route {...rest} render={props => (
            localStorage.getItem("authToken") ?
                <Component {...props} />
            : <Redirect to="/signup" />
        )} />
    );
};

export default Privateroute;

App.js

import React, { Component } from 'react';
import { BrowserRouter, Switch } from 'react-router-dom';
import Privateroute from './components/PrivateRoute';

class App extends Component {

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Privateroute component={Register} path="/signup" exact />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;

如果你想首先考虑道具,你必须了解函数中的参数。

在函数中,您可以调用带参数的函数。参数是可选的,如果你传递它将传递值,如果你不传递它将是空的。有时,如果您在函数定义中为参数使用默认值,它将保留该值。

让我们来谈谈道具吧。道具与参数相同。但是在这种情况下。 React 会为你做这件事,而且它是动态的。无论您将通过组件传递什么 props 并在默认情况下做出反应,都会传递一些额外的 props。

所以如果你使用任何全局组件,props 都是由 react 自动生成的。如果您使用 react-router-dom 浏览器路由器,则会传递或创建 historylocation 等。

终于。一言以蔽之,道具与参数相同,反应也动态创建圆顶。