打字稿:TypeError 未定义

我对打字稿和反应相当陌生。我一直在尝试实现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。最好的解决方法是什么?


湖上湖
浏览 131回答 3
3回答

慕田峪9158850

它与 TypeScript 无关。TS 只是一个编译器和 linter,您会收到运行时错误。这是这一行:this.reward.rewardMe()在ref获取充分组件后坐骑分配并rewardMe()试图立即调用它。这也是次要错误。您不想使用()调用或函数将立即触发(并且永不停止)。该行应该是<Button&nbsp;onClick={this.reward.rewardMe}&nbsp;style={styles.button}&nbsp;variant="contained"&nbsp;color="primary">

米脂

将您的更改onClick为这样的:onClick={()&nbsp;=>&nbsp;{this.reward.rewardMe()}}

繁星淼淼

因为我从来没有使用过这个方案,但根据文件/我可能是错的使用率话题。他们没有初始化reward变量。尝试删除它,这是固定版本type Props = {}class Surprisebutton extends Component<Props>{render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Reward&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ref={(ref) => { this.reward = ref }}&nbsp; &nbsp; &nbsp; &nbsp; type='memphis'>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Button onClick={this.reward.rewardMe()} style={styles.button} variant="contained" color="primary">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Surprise!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <FavoriteIcon style={{ marginLeft: 10 }} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Button>&nbsp; &nbsp; &nbsp; &nbsp; </Reward>&nbsp; &nbsp; )&nbsp; }}再说一次,我可能是错的,但根据 github 页面,我认为这是我唯一可以推断的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript