渲染道具-反应路线

Sho*_*cob 3 reactjs react-router-v4

const Home = () => <div>Home</div>

const App = () => {
  const someVariable = true;

  return (
    <Switch>
      {/* these are good */}
      <Route exact path='/' component={Home} />
      <Route
        path='/about'
        render={(props) => <About {...props}  />}
      />
    </Switch>
  )
}

const About = (props) => {
  return (
    <div>
      About   
    </div>
  )
} 
Run Code Online (Sandbox Code Playgroud)

在代码示例中,位于

<Route
        path='/about'
        render={(props) => <About {...props}  />}
      />
Run Code Online (Sandbox Code Playgroud)

当react遇到作为react-router一部分的Route组件的render prop时,它将传递什么props?

给定https://reactjs.org/docs/render-props.html上的文档,渲染道具是组件用来了解要渲染什么的功能道具,值传递给埋在Route声明中的道具吗?反应路由器

sar*_*eek 6

我们将 Route 与渲染道具一起使用,

<Route path = "/about" component={About} />
Run Code Online (Sandbox Code Playgroud)

或者,

<Route path = "/about" render= { (props) => <About {...props} } />
Run Code Online (Sandbox Code Playgroud)

第二个与第一个不同,因为在第二种情况下,About 组件可以访问通过 Route 传入的 props。

比如说,有一个 Profile 组件,

<Route path="/admin/profile"
       render={ props => (
              <Profile tabs= {"valuePassed"} {...props}  />  
        )}
 />
Run Code Online (Sandbox Code Playgroud)

现在在 Profile 组件中,我们可以访问所有道具,

this.props.tabs 在基于类的组件中提供“valuePasses”,而 props.tabs 用于功能组件。

希望这可以帮助。


jen*_*ens 5

道具通过Route组件传递给render prop方法。您可以在React Router源代码中看到这一点。由Route组件传递的道具有match, location, history, staticContext。如果要使用来自父组件的props(在其中定义render props方法),则可以省略props参数。

render={() => <About {...props} />}

然后,您将从包含路线的组件中获取道具。

您提供的示例没有多大意义,因为它仅使用Route上的“ component”道具来复制您获得的行为。

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js#L120