点击按钮时 Reactjs 调用另一个组件

问题描述

目前,我正在开发一个简单的系统,按下按钮后会打开另一个网页。但是,我的目标是在单击按钮后显示一个组件。因此,我初始化了一个布尔值设置为 false 的状态。此外,在单击按钮后,状态应设置为 true,这将启用组件 ApartmentBooking01 的显示。运行代码时,由于 history.push 对象会出现一个新网页。但是,它没有显示我想要的组件 ApartmentBooking01。任何人都可以向我解释我做错了什么吗?

class Apartmentinformation01 extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      showBookinginformation: false,apartmentinformation: [{
        apartmentNumber: [],availablebeds: [],pricePerNight: []
      }]
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    this.props.history.push("api/apartments/apartmentbooking01");
    this.setState({
      showBookinginformation: !this.state.showBookinginformation
    });
    
  }

  getApartmentBookingComponent(){
    if(this.state.showBookinginformation){
      return <ApartmentBooking01/>
    }else {
      return null;
      
    }
  }

  componentDidMount() {
    axios.get(`http://localhost:8080/api/apartment/`)
      .then(res => {
        const apartmentinformation = res.data;
        this.setState({ apartmentinformation });

      })
  }


  render() {
    const { apartmentinformation } = this.state;

    return (

      <div className='apartmentinformation-container'>

        <ul>
          {
            apartmentinformation.filter(apartmentInfo => apartmentInfo.apartmentNumber == 1)
              .map(filteredApartment => (
                <div className='apartmentinformation-items'>
                  <h2 className='apartmentssection-01-price'>Price per Night</h2>
                  <p className='apartmentinformation-items-pricePerNight'>€{filteredApartment.pricePerNight},-  </p>
                  <h2 className='apartmentssection-01-beds'>Available beds</h2>
                  <p className='apartmentinformation-items-availablebeds'>{filteredApartment.availablebeds} beds</p>
                </div>

              ))
          }
        </ul>
   
        <button variant="btn-success" onClick={this.handleClick}>More information</button>
        {this.getApartmentBookingComponent}
   
      </div>




    )

  }


}

export default withRouter (Apartmentinformation01)

解决方法

尝试在 price: productData['price'], 函数中添加 event.preventDefault()。这应该在第一行。

你也应该为你的映射方法添加键:

handleClick

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...