我对Typescript和React很新。我一直在尝试实现react-rewardsnpm库,除了一个问题我已解决了所有问题。type Props = {}class Surprisebutton extends Component<Props>{
reward: any;
render() {
return (
<Reward
ref={(ref) => { this.reward = ref }}
type='memphis'>
<Button onClick={this.reward.rewardMe()} style={styles.button} variant="contained" color="primary">
Surprise!
<FavoriteIcon style={{ marginLeft: 10 }} />
</Button>
</Reward>
)
}}跑完后npm start我得到一个错误TypeError: this.reward is undefined。什么是最好的解决方法?
2 回答
慕容708150
TA贡献1831条经验 获得超4个赞
它与TypeScript无关。TS只是一个编译器和linter,你得到一个运行时错误。就是这条线:
this.reward.rewardMe()
在ref被分配后的组件完全安装并rewardMe()试图立即调用它。这也是次要的错误。您不想使用()调用或函数将立即触发(并且永不停止)。
这条线应该是
<Button onClick={this.reward.rewardMe} style={styles.button} variant="contained" color="primary">
拉丁的传说
TA贡献1789条经验 获得超8个赞
因为我从来没有使用过这个方案,但根据文件/我可能是错的使用率话题。它们不是初始化reward变量。尝试删除它,这是固定版本
type Props = {}class Surprisebutton extends Component<Props>{render() {
return (
<Reward
ref={(ref) => { this.reward = ref }}
type='memphis'>
<Button onClick={this.reward.rewardMe()} style={styles.button} variant="contained" color="primary">
Surprise!
<FavoriteIcon style={{ marginLeft: 10 }} />
</Button>
</Reward>
)
}}我可能错了,但根据github页面,我认为这是我唯一可以推断的东西。
添加回答
举报
0/150
提交
取消
