为什么我不能在React中渲染之前声明一个函数?

时间:2017-03-28 15:06:06

标签: javascript function reactjs methods

所以我的代码可以工作,但如果我将handleClick()移动到渲染器,它将抛出一个错误。如果我尝试声明像

这样的函数,也一样

var handleClick = () => { this.setState({reservationVisible: true}) console.log(this.state.reservationVisible)}

外部渲染。

当我将handleClick()作为道具传递时,我需要调用{this.handleClick.bind(this)},当我使用在渲染内部声明的函数时,{handleClick.bind(this)是足够。我真的不明白为什么。我应该在哪里声明功能呢?外部或内部渲染?我应该使用函数还是方法?

这是我的代码:

import React, { Component } from 'react';
import Room from './Room'
import Form from './Form'

class Rooms extends Component {

  constructor(props){
    super(props);
    this.state = {reservationVisible: false}
  }

    handleClick(e){
        this.setState({reservationVisible: true})
        console.log(this.state.reservationVisible)
      }

  render(){


      let rooms = [
        {
          roomNumber: '1',
          type: 'Cool room',
          price: '130 $',
          goods: ['radio', 'phone']
        },
        {
          roomNumber: '2',
          type: 'Cozy Room ',
          price: '165 $',
          goods: ['radio', 'phone, tv']
        },
        {
          roomNumber: '3',
          type: 'Dirty Room',
          price: '130 $',
          goods: ['balcony', 'phone']
        },
        {
          roomNumber: '4',
          type: 'Like Real Dirty Room',
          price: '90 $',
          goods: ['fridge', 'phone', 'balcony']
        }
      ]

      let getElements = (room, i) => {
        return(
          <Room
            key={i}
            roomNumber={room.roomNumber}
            type={room.type}
            price={room.price}
            goods={room.goods.map(good => good + ", ")}
            onClick={this.handleClick.bind(this)}
          />
        )
      };
      let roomsMapped = rooms.map(getElements);

    return(
      <div>
        {roomsMapped}
      </div>
    )
  }
}

export default Rooms

和房间组件

import React, { Component } from 'react';


class Room extends Component{
  render(){
    return (
      <div className="room">
        <div className="image"><h1>Image nr {this.props.roomNumber}</h1></div>
        <div className="buttonGroup">
          <div className="button galleryButton">Gallery</div>
          <div className="button reserve" onClick={this.props.onClick.bind(this)}> I'll take it</div>
        </div>
        <div className="info">
          <div className="topInfo">
            <span className="left">{this.props.type}</span>
            <span className="right">{this.props.price}</span>
          </div>
          <div className="additional">
            {this.props.goods}
          </div>
        </div>
      </div>
    )
  }
}

export default Room

0 个答案:

没有答案