简体   繁体   English

React.js 道具问题

[英]React.js props issue

this is probably a very basic question.这可能是一个非常基本的问题。 im making a settings page for my site and I need some help.我正在为我的网站制作一个设置页面,我需要一些帮助。

<Route path="/conversations/settings" render={props => <Setting isNew colorMode=
{props.colorMode} toggleColorMode={props.toggleColorMode}/>}/>

so what I want this to do ideally is when you click a button on the settings page it enables/disables darkmode.所以我最理想的做法是,当您单击设置页面上的按钮时,它会启用/禁用暗模式。 In this situation it doesnt.在这种情况下它不会。 but if I write it like this但如果我这样写

<Setting colorMode={props.colorMode} toggleColorMode={props.toggleColorMode}/>

I can actually enable/disable darkmode, but this means the settings page renders on every page of the website which of course, I dont want.我实际上可以启用/禁用暗模式,但这意味着设置页面呈现在网站的每个页面上,这当然是我不想要的。

Since you say that <Setting colorMode={props.colorMode} toggleColorMode={props.toggleColorMode}/> works I'll assume that wherever you are rendering this Setting component that props is in scope and has the prop values you want.既然你说<Setting colorMode={props.colorMode} toggleColorMode={props.toggleColorMode}/>有效,我假设无论你在哪里渲染这个Setting组件, props都在 scope 中并且具有你想要的道具值。

If you are wanting to render Setting on a route and pass other non-route-props though then you are correct to use the render prop to do so.如果您想在路由上渲染Setting传递其他非路由道具,那么使用render道具这样做是正确的。 The issue you've now is that you are accessing the passed route props instead of your props object that is in scope.您现在遇到的问题是您正在访问传递的路线道具,而不是 scope 中的props object。 Rename the route props to something other than the props of the outer parent component and spread these into your Setting component if you need them.将路由 props 重命名为外部父组件的props以外的名称,并在需要时将它们传播到您的Setting组件中。

<Route
  path="/conversations/settings"
  render={routeProps => (
    <Setting
      {...routeProps} // <-- history, location, & match
      isNew
      colorMode={props.colorMode}             // <-- you props
      toggleColorMode={props.toggleColorMode} // <-- your props
    />
  )}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM