onClick功能无需点击即可运行

时间:2018-03-19 17:56:47

标签: javascript reactjs

我的ReactJS代码遇到问题导致onClick错误,我无法理解。

<button onClick={this.apiGetProductPicture(this.props.categorie)}>{this.props.name}</button>

如果我这样写(没有参数可以工作)

<button onClick={this.apiGetProductPicture()}>{this.props.name}</button>

但是使用参数时,该功能在我加载页面时起作用,而不需要单击...

我给出参数的示例。

<ProductItem name={"Boulangerie"} categorie={0} />

我已经搜索但不明白为什么函数在未经许可的情况下启动。

功能:

    apiGetProductPicture(i) {
    console.log('apiGetProductPicture');
    var json = myApiGet('https://******')
        // TODO do something with the data
        .then(json => this.setState({ pictures: json.content.categories[1].background }))

        .catch(error => console.log('home2', error));
}

1 个答案:

答案 0 :(得分:0)

你必须在onClick上提供一个函数的引用:

所以你必须写出类似的东西:

apiGetProductPicture= (i) => () => {
    i = 0;
    console.log('apiGetProductPicture');
    var json = myApiGet('https://******')
        // TODO do something with the data
        .then(json => this.setState({ pictures: json.content.categories[1].background }))

        .catch(error => console.log('home2', error));
}
相关问题