【问题标题】:I can't figure out how to do a switch in React with two components我不知道如何在 React 中使用两个组件进行切换
【发布时间】:2021-09-20 07:08:21
【问题描述】:

我希望能够在一个文件的组件之间切换。我希望 ShowAccount 成为默认值。一个显示 EditAccount 的按钮,它会隐藏 ShowAccount。

模拟我的想法:

import React from 'react';
import EditAccount from './editacc';
import ShowAccount from './showacc';

const Toggle = () => {
    return(
        <>  
            if (EditAccount === Active) {
                hide <ShowAccount />
                show <EditAccount />
            } else {
                show <ShowAccount />
            }
        </>
    );
};

export default Toggle;

索引.js

import React from 'react';
import './acc.css';
import Header from '../../../Header';
import Toggle from './content/toggle';

const Myaccount = () => {
  return (
    <>
      <Header />
      <br />
      <Toggle />
    </>
  );
};
export default Myaccount;

【问题讨论】:

  • 这完全没有意义。你在 JSX 中有一个条件 statement,你只能有 expressions (即使这样它们也必须用大括号括起来),你正在将一个组件与未定义的组件进行比较变量 Active,并且您随机发明了显示和隐藏运算符。
  • 我说这是我想要它做的模型。显然,它不会那样工作,或者它会......我要说的是,如果一个组件正在显示,我希望另一个组件被隐藏。我不打算让别人认为我实际上是在尝试这样做。 @jonrsharpe
  • 我建议你阅读例如reactjs.org/docs/conditional-rendering.html,而不仅仅是猜测。

标签: reactjs


【解决方案1】:

您可以使用状态处理并渲染条件组件。

import React from 'react';
import EditAccount from './editacc';
import ShowAccount from './showacc';

const Toggle = () => {
    const [isEditAccount, setEditAccount] = React.useState(false);
     
    const handleToggleView = () => {
       setEditAccount(!isEditAccount)
    };

    return ( 
      <>
      <button onClick={handleToggleView} >
       Toggle View
      </button>
      {isEditAccount ? <EditAccount /> : <ShowAccount />} 
      </>
    );
};

export default Toggle;

【讨论】:

    【解决方案2】:

    https://codesandbox.io/s/react-new?file=/src/App.js

    class App extends React.Component {
      state = {
        isAcc: true
      };
    
      render() {
        return (
          <div>
            <button onClick={() => this.setState({ isAcc: !this.state.isAcc })}>
              Toggle View
            </button>
            {this.state.isAcc ? <Acc /> : <Edit />}
          </div>
        );
      }
    }
    const Acc = () => <h1>Account</h1>;
    const Edit = () => <h1>Edit</h1>;
    
    ReactDOM.render(<App />, document);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2019-09-05
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多