reactJS渲染调用带参数的函数无法编译

问题描述 投票:0回答:4

我有一个reactJS应用程序与以下代码动态呈现输出:

    renderData = () => {   

    return this.state.data.map( data => (
        <div>
            <div className="oldscanFont">
                <img className="resize" src={data.galleryURL}></img><label>&nbsp;&nbsp;&nbsp;Price:&nbsp; {data.sellingStatus[0].currentPrice[0]['__value__']}</label><br />
                <label> {data.title} </label>
            </div>                    
            <div>
                <button className="btnStartScan"
                    type='button'     
                    onClick={() => { 
                    this.saveData(this.barcode, {data.title}, {data.galleryURL}, {data.sellingStatus[0].currentPrice[0]['__value__']} );
                    }}>
                    Save
                </button>                    
            </div> 
        </div>
    ) )
}

我想要做的是当用户点击生成的按钮时调用函数this.saveData。另外,我想将一些参数传递给saveData。问题是我的编辑器标记'。'在我希望传递的所有参数中,除了this.barcode之外。换句话说,我被标记为'。'在参数{data.title}中。 {data.title}有效,因为它出现在saveData函数调用之上几行。

将这几个参数传递给saveData函数的正确语法是什么?

谢谢。

javascript reactjs
4个回答
1
投票

您不需要在大括号内再次使用大括号。大括号意味着你指的是JSX中的Javascript代码。您可以将一对括号内的所有内容视为纯JS。删除onClick属性中的大括号,如下所示:

<button className="btnStartScan"
        type='button'     
        onClick={() => { 
            this.saveData(this.barcode, data.title, data.galleryURL, data.sellingStatus[0].currentPrice[0]['__value__'] );
        }}/>

0
投票

你的对象需要密钥:

this.saveData(this.barcode, {data.title}, {data.galleryURL}, {data.sellingStatus[0].currentPrice[0]['__value__']} );

应该:

this.saveData(this.barcode, {title: data.title}, {galleryUrl: data.galleryURL}, {value: data.sellingStatus[0].currentPrice[0]['__value__']} );

您可以使用对象键/值的简写,但您必须使用标识符而不是表达式:

const { title, galleryURL } = data;
const value = data.sellingStatus[0].currentPrice[0]['__value__'];

this.saveData(this.barcode, {title}, {galleryURL}, {value} );

另外我不确定你的意图是将对象传递给saveData。当你已经在一个转义组({}的值)时,你不需要在JSX中的onClick中包装变量。


0
投票

您应该使用按钮的数据集和值属性以及单击处理程序作为参考。

<button 
    value={mainValueVariable}
    data-title={data.title}
    data-gallery-url={data.galleryUrl}
    className="btnStartScan" 
    type='button' 
    onClick={this.saveData}>
    Save
</button>

然后在单击处理函数中,它也存在于Component Class中,当前的renderData方法是:

saveData = event => {
    const { value, dataset } = event.target
    const { galleryUrl, title } = dataset;

    ... do something with value and dataset thingies
}

0
投票

我建议你在函数中传递数据对象:

this.saveData(this.barcode,data)

然后,在saveData函数中,使用数据选项:

saveData(barcode, data) {
const {title, galleryURL, sellingStatus} = data
//now, work through title, galleryURL, sellingStatus
© www.soinside.com 2019 - 2024. All rights reserved.