首页 > 解决方案 > this.props.chatVisible 是“未定义”

问题描述

我想在 ChatTitleButton 类中使用 chatVisible 道具。但是当我 console.log(this.props.chatVisible); 我会变得不确定。而且我不知道为什么我一直不确定。因为它必须用作布尔值,所以 React 可以根据该变量呈现要呈现的 html。我希望有人能帮助我

import ChatTitleButton from "./ChatTitleButton";

class Chat extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      chatVisible: true,
    };
  }
  render() {
    return ( 
    <div classname = "chat-widget" >
      <ChatTitleButton / >
    </div>
    )
  }
}
import React from 'react';

export default class ChatTitleButton extends React.Component {
  render() {
    if (this.props.chatVisible === true) {
      return ( <
        div className = "chat-title-close" >
        <
        button onClick = {
          this.closeChat
        }
        className = "btn chat-close" > Chat beindigen < /button> <
        /div>

      )
    } else {
      return ( <
        div className = "chat-title-close" >
        <
        button onClick = {
          this.openChat
        }
        className = "btn chat-close" > Chat openen < /button> <
        /div>
      )
    }

  }
}

标签: reactjs

解决方案


您没有将道具传递给组件。在您的渲染语句中,而不是<ChatTitleButton />使用<ChatTitleButton chatVisible={this.state.chatVisible}/>.


推荐阅读