从子组件中调用父组件函数

时间:2020-08-08 03:25:55

标签: javascript reactjs

这是React的新手。我的爱好项目网站中有一个彩票盘: Wheel对象是通过npm下载的:

npm install lottery-wheel
import Wheel from 'lotter-wheel'
class Lottery extends Component {
   constructor() {
     bla bla 
   }
  
  componentDidMount() {
     new Wheel( {
        el: document.querySelector("#wheel"),
            onSuccess(data) {
              alert(`Congratulations, you picked up ${data.text}`)
              /* I want to pass the data here to Parent */ 
            },
            onButtonHover(anime, button) {
                anime({
                  targets: button,
                  scale: 1.3,
                  perspective: 80,
                  duration: 400
                });
            },
     });
  }

  render() {
  
    return (
      <div id="wheel"></div>
    )
  }
}

因此,在回调函数“ onSuccess”中,我要将“数据”从Wheel子组件传递到“ Lottery”父组件。

我该怎么做?我知道道具如何工作,但在这种情况下不行。.在这种情况下,我可以使用挂钩吗? 我想避免下载并进入“车轮”定义,因为它不是我创建的。

1 个答案:

答案 0 :(得分:1)

定义一个函数,并将其设置为onSuccess中的Wheel回调。

class Lottery extends Component {
  successHandler = data => {
    alert(`Congratulations, you picked up ${data.text}`);
  };

  componentDidMount() {
    new Wheel({
      el: document.querySelector("#wheel"),
      data: [{
        text: 'apple',
        chance: 20
      }, {
        text: 'banana'
      }, {
        text: 'orange'
      }, {
        text: 'peach'
      }],
      onSuccess: this.successHandler,
      onButtonHover(anime, button) {
        anime({
          targets: button,
          scale: 1.3,
          perspective: 80,
          duration: 400
        });
      }
    });
  }

  render() {
    return <div id="wheel"></div>;
  }
}

Edit call-a-parent-component-function-from-a-child-component