【问题标题】:Cant render Component in switch statement in React无法在 React 的 switch 语句中渲染组件
【发布时间】:2020-11-09 21:33:04
【问题描述】:

我有一个 registration 视图,在我的表格中我有命令显示带有确认的模式:

(...)               
render: (rowData) => (
  <button
    onClick={() => RenderModals(rowData, 'DELETE_USER_MODAL')}
  >
    Remove
  </button>
),
(...)

我的 RenderModals 函数如下所示:

type RenderModalProps = {
  data: any;
  modalCommand: string;
};

export const RenderModals = (data, modalCommand) => {
  console.log(data);
  switch (modalCommand) {
    case 'DELETE_USER_MODAL':
      return <DeleteUserModal data={data} />;
    case 'SOME_MODAL':
      return console.log('some modal');
    default:
      undefined;
  }
};

我可以在上面的示例中看到 console.log(data)。但是...我无法从 DeleteUserModal 组件中看到任何 console.log。

删除用户模式:

type DeleteUserModalProps = {
  data: any;
};

export const DeleteUserModal = ({ data }: DeleteUserModalProps) => {
  console.log(`show data  ${data}`);
  return <div>some text...</div>;

};

我不知道我做错了什么?

为什么来自 DeleteUserModal 的 console.log 没有触发?

【问题讨论】:

  • 您从未真正呈现 DeleteUserModal。您所做的只是将它返回给 onClick 函数。
  • @RedFox - 我如何以上述组件排列方式呈现 DeleteUserModal?
  • 最简单的方法可能是将组件分配给状态变量,然后渲染它。
  • 使用RenderModals在状态中设置一个布尔值(如showDeleteModal),然后有条件地在返回中渲染模态({state.showDeleteModal &amp;&amp; &lt;DeleteuserModal /&gt;})。

标签: javascript reactjs switch-statement components rendering


【解决方案1】:

按照您目前的设置方式,这将起作用:

class RegistrationExampleOne extends React.Component {
    constructor(props) {
        super(props);
        this.state = {component: null};
    }

    render() {
        return (
            <div>
                <button onClick={() => this.setState({component: RenderModals(rowData, 'DELETE_USER_MODAL')})}>Remove</button>
                {this.state.component}
            </div>
        );
    }
}

选项一不一定是更好的做事方式,但它更有活力。

选项二(如 @Brian Thompson 在 cmets 中提到的)将与此类似:

import DeleteModal from './path';

class RegistrationExampleTwo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {showDeleteModal: null};
    }

    render() {
        return (
            <div>
                <button onClick={() => this.setState({showDeleteModal: true})}>Remove</button>
                {this.state.showDeleteModal && <DeleteModal data={rowData} />}
            </div>
        );
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2020-06-13
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    相关资源
    最近更新 更多