【问题标题】:Change content when clicks the button with reactjs & Material UI单击带有 reactjs 和 Material UI 的按钮时更改内容
【发布时间】:2020-03-20 13:12:16
【问题描述】:

该网站正在使用 Reactjs 和 Material UI 开发。

Switch 语句用于在每次更改地址时输出不同的组件。并且按钮应该使用“链接到”移动到 URL。

但我不明白,当我按下按钮时,它不会更改为该组件,但是当我按下“抽屉”按钮时,它会更改为该组件。

我想知道问题是什么。 我认为问题出在以上三个方面。但是完整的工作代码也在这里与 CodeSandbox CodeSandbox URL

[部分 switch 语句]

let contentPlace;
let changePage = () =>{
  let location = window.location.pathname;
  console.log(location);
  switch(location){
    case '/':{
      contentPlace=<Home />
      break;
    }
    case '/login':{
      contentPlace=<SignIn/>
      break;
    }
  }
}  

[部分按钮]

<Button variant="outlined" color="inherit" onClick={changePage()}>
  Login
</Button>
</Link>
<Link to="/" className="home">
<Button variant="outlined" color="inherit"  onClick={changePage()}>
  HomE
</Button>

[部分带有 React-dom-Router 的 Switch]

<Switch>
  <Route path="/login">
    {/* <SignIn /> */}
  </Route>
  <Route path="/about">
    {/* <About /> */}
  </Route>
  <Route path="/users">
    {/* <Users /> */}
  </Route>
  <Route path="/">
  </Route>
    {/* <Home /> */}
</Switch>

它是这样工作的。

【问题讨论】:

  • 我认为你应该在react-router-dom中使用&lt;Link&gt;组件,你的onClick={changePage()}也应该改为onClick={changePage}
  • 仅供参考,您的沙盒工作不正常。
  • 为什么这个问题会在 node js 中被标记?

标签: javascript node.js reactjs react-router material-ui


【解决方案1】:

我不太确定您为什么需要一个开关盒。但是你可以看看这个简单的例子。你不需要用Link 包裹你的Button,而是可以在Button 中使用component 属性来防止对组件进行不必要的包裹。

const SignIn = () => (
  <div>
    This is sign in page.
    <Button component={Link} to="/home">
      To Home Page
    </Button>
  </div>
)

const Home = () => (
  <div>
    This is home page.
    <Button component={Link} to="/login">
      To Login Page
    </Button>
  </div>
)

const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/login">
          <SignIn />
        </Route>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
    </BrowserRouter>
  )
}

【讨论】:

  • 因为我必须把它放在主要部分。在主要部分有 contentPlace 变量。我认为这是有效的,但它不起作用。 &lt;Switch&gt; &lt;Route path="/login"&gt;{(contentPlace = &lt;SignIn /&gt;)}&lt;/Route&gt; &lt;Route path="/about"&gt;{/* &lt;About /&gt; */}&lt;/Route&gt; &lt;Route path="/users"&gt;{/* &lt;Users /&gt; */}&lt;/Route&gt; &lt;Route path="/"&gt;{(contentPlace = &lt;Home /&gt;)}&lt;/Route&gt; &lt;/Switch&gt;
  • 你的意思是loginhome 都在/ 的路径中吗?
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多