Newby React项目帮助:
我正在尝试将组件的状态传递给子组件,以便它可以加载图像。gift1的状态最初为null。按下按钮时,它会切换显示子组件,并将gift1设置为具有图像详细信息的对象。下面是在父组件中设置的切换,其中this.state.giftContainer用于切换子组件: GiftBoxAnimation。它还将gift1状态作为礼物属性传递给子对象。
let display = this.state.giftContainer && this.state.giftContainer === true 
  ? (<GiftBoxAnimation gift={this.state.gift1} />)
  : null;当父组件中的按钮被按下时,generateItems()将触发并将gift1的状态设置为该对象,然后切换子对象
  generateItems = (e) =>{
  //Insert code here that sets state of gift1: {name: "giftImage"}
    this.setState({
      giftContainer: true
    });
  }子组件如下所示:
  <Spritesheet
    className={"sprite-gift"}
    image={"/images/"+this.props.gift+".png"}
    widthFrame={1024}
    heightFrame={1024}
    steps={5}
    fps={5}
    autoplay={true}
    loop={true}
  />当我尝试使用this.props.gift获取图像数据时,它返回原始设置的gift1 null状态。第二次按下父组件上的按钮时,将返回一个对象。但是,如果我尝试使用this.props.gift.name访问该图像,则它是undefined。
如何将父状态传递给子组件,以便在父组件第一次按下按钮时显示子组件中的图像?
发布于 2019-01-16 10:51:20
如果为空,则更改以下代码以传递空对象
let display = this.state.giftContainer 
&& this.state.giftContainer === true 
?(<GiftBoxAnimation gift={this.state.gift1 || {}}/>)
:(null);https://stackoverflow.com/questions/54209558
复制相似问题