渲染组件onClick

时间:2019-09-25 16:37:14

标签: typescript react-redux

可能重复。我已经尝试了其他几篇文章中的解决方案,但是我的解决方案仍然无法正常工作。我正在尝试从onClick渲染组件。 函数getModal()被调用并显示console.logs,但未呈现该组件。任何解决方案或建议,将不胜感激。

所有代码均为摘要

这是我的TestGroup.tsx

export class ListGroup extends React.Component<IProps> {
  getModal = () => {
    return (
      console.log("hello"),
      console.log("world"),
      (
        <TestGroup
          tesyState={this.props.testState}
          onUpdateSelectedTest={this.props.onUpdateSelectedTest}
        />
      )
    );
  };

  public render() {

    return (
      <div>
        <ul
          className="list-group"
          style={{
            marginTop: "20px",
            display: "inline-block"
          }}
        >
          {filterTest.map(filterTest => (
            <li
              className="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
              onClick={() => {
                this.props.onUpdateSelectedTest(filterTest);
                this.getModal();
              }}
            >
              {filterTest.testPN}: {filterTest.description}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

这是我的QuestionGroup.tsx: 我将渲染一个模态,但作为测试,我只想看到“ Hello World”

export class QestionGroup extends React.Component<IProps> {

  public render() {
    //const onAfterOpenFn = () => {};
    //const onAfterCloseFn = () => {};

    return (
      <div>
        <h1>HELLO WORLD</h1>

      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

onClick方法不会呈现返回的组件。

您必须添加一个state变量以显示/隐藏模式:

interface IState {
  showModal: boolean;
}

export class ListGroup extends React.Component<IProps, IState> {
  // Define a state variable to show/hide the modal
  public state: IState = {
    showModal: false
  };

  showModal = () => {
    // Show the modal
    this.setState({ showModal: true });
  };

  public render() {
    const { showModal } = this.state;

    return (
      <div>
        <ul
          className="list-group"
          style={{
            marginTop: "20px",
            display: "inline-block"
          }}
        >
          {filterTest.map(filterTest => (
            <li
              className="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
              onClick={() => {
                this.props.onUpdateSelectedTest(filterTest);
                this.showModal(); // <-- Function has been renamed
              }}
            >
              {filterTest.testPN}: {filterTest.description}
            </li>
          ))}
        </ul>
        // Show the modal if showModal is true
        {showModal && (
          <TestGroup
            tesyState={this.props.testState}
            onUpdateSelectedTest={this.props.onUpdateSelectedTest}
          />
        )}
      </div>
    );
  }
}