微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决点击按钮时 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?