如何在reactjs中一次渲染一个可重用组件?

时间:2019-07-03 08:29:39

标签: reactjs

我将Chat组件两次重用到另一个组件中。单击“聊天”按钮时显示,但彼此重叠。

if(...)break;

我希望一次显示一个聊天。当我单击“聊天”按钮2并显示“聊天1”时,应该隐藏“聊天1”。

1 个答案:

答案 0 :(得分:1)

本质上,您需要为每个Chat组件提供一个标识符,并跟踪当前打开的组件。

这是父项组件的基本结构:

class App extends React.Component {
  state = {
    currentChatId: null
  };

  handleOpen = id => {
    this.setState({
      currentChatId: id
    });
  };

  render() {
    return (
      <div>
        <Chat
          identifier={1}
          currentChatId={this.state.currentChatId}
          handleOpen={this.handleOpen}
        />
        <Chat
          identifier={2}
          currentChatId={this.state.currentChatId}
          handleOpen={this.handleOpen}
        />
      </div>
    );
  }
}

因此请注意,我们给每个Chat组件一个identifier道具。我们将使用identifier更新活动聊天-我们将其存储为名为currentChatId的父状态。这一切都是通过handleOpen()事件处理程序完成的,我们也将其作为Chat的支持对象。

现在在您的Chat组件中,我们需要为open()componentDidUpdate()配置逻辑

class Chat extends React.Component {
  constructor() {
    super();
    this.state = {
      show: false
    };
  }

  componentDidUpdate(prevProps) {
    const { identifier, currentChatId } = this.props;

    if (this.props.currentChatId !== prevProps.currentChatId) {
      this.setState({
        show: identifier === currentChatId ? true : false
      });
    }
  }

  open = () => {
    const { identifier, handleOpen } = this.props;
    handleOpen(identifier);
  };
  render() {
    return (
      <div className="chat">
        <button className="btn-yes round" onClick={this.open}>
          {this.props.title}
        </button>
        {this.state.show && (
          <div className="show-chat">
            <div className="chat-head">
              Now Chatting{" "}
              <i className="fas fa-angle-down" onClick={this.close} />
            </div>
            <div className="chat-body">
              <div className="blue">
                Teresa wants to chat about her healthcare finances
              </div>
              <ul>
                <li>
                  <img src={""} alt="chat agent avatar" />
                </li>
                <li>
                  <h6>John Newman</h6>
                  <div className="gray">Hi Teresa!</div>
                  <div className="gray">
                    Here is the <a href="/">link to the finance tool</a> we
                    discussed.
                  </div>
                  <div className="gray">
                    If you have any questions, let me know!
                  </div>
                </li>
              </ul>
            </div>
            <input placeholder="Type here and hit enter to chat" />
          </div>
        )}
      </div>
    );
  }
}

工作流程:

  1. 用户单击“聊天”按钮之一,触发handleOpen(),我们 传递唯一的identifier ....
  2. 该信息将传递回Parent,现在传递到currentChatId 应该用identifier ...
  3. 更新
  4. currentChatId作为 currentChatId道具...
  5. 在所有聊天组件上触发
  6. 触发componentDidUpdate(),我们检查 currentChatId与自己的标识符相对应,则只有一个 匹配,因此我们将其显示出来。

有关工作示例,请参见codeandbox:https://codesandbox.io/s/react-example-kgm2h