onChange事件无法正确将参数传递给我的函数

时间:2019-10-03 09:10:25

标签: javascript reactjs onchange

所以基本上,我的输入中有一个onChange事件,用于更改图片。我尝试在.map中执行此操作,因为有多个图片,因此我有一个称为“ i”的“计数器”,该计数器可以跟踪要尝试修改的图片。我遇到的问题是,当我尝试通过oni事件中的参数之一传递“ i”时,无论我试图修改哪张图片,“ i”始终等于0。

这是针对社交媒体之类的网站,人们可以在其中修改个人资料图片。我试图在onChange事件发生之前声明一个新变量并将其设置为等于“ i”,但这也不起作用

let data = this.state.results.map((item, i) => {
    return (
        <tr key={i}>
            <td>
                <Profile id="profile" className="d-flex justify-content-center">
                    {
                        this.state.accounts[i].profilePicture ?
                        <>
                            <RoundedProfile size="50px" id="roundedProfile" className="profilePicture" shadowed src={ settings.apiUrl + this.state.accounts[i].profilePicture }
                             />
                             <div id="changeProfilePicture" onClick={this.changeProfilePicture}>
                                 <FontAwesomeIcon icon={faPen}/>
                             </div>
                             <input
                             type="file"
                             id="inputProfilePicture"
                             accept="image/png, image/jpeg"
                             value={this.state.profilePicture ? this.state.profilePicture : ""}
                             onChange={(event) => this.handleChangeProfile(event, i)}
                             />
                         </>
                         :
                         <>
                         <div id="changeProfilePicture" onClick={this.changeProfilePicture}>
                             <FontAwesomeIcon icon={faPen}/>
                         </div>
                         <input
                         type="file"
                         id="inputProfilePicture"
                         accept="image/png, image/jpeg"
                         value={this.state.profilePicture ? this.state.profilePicture : ""}
                         onChange={(event) => this.handleChangeProfile(event, i)}
                         />
                     </>
                     }
                 </Profile>
             </td>

所以我希望“ i”等于与其关联的个人资料图片

2 个答案:

答案 0 :(得分:0)

您应该向我发送第一个参数: 您的代码:onChange={(event) => this.handleChangeProfile(event, i)} 并更改为onChange={(event) => this.handleChangeProfile(i,event)} 了解更多 https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

答案 1 :(得分:0)

您可以乘坐'event',使用'currentTarget.value property'并分配onChange,如下所示:

class test extends React.Component{
    state = {trKey: 0}

    handleChangeProfile = (id)=>{
     /**your instructions**/
     this.setState({trKey: i.currentTarget.value })
    }

    render(){
    return(
           /****/
           onChange = {this.handleChangeProfile}
    )

} }