2017-07-09 36 views
0

我有一個數組,我想從用戶的輸入中添加一個新名稱。在我的部分,我有:當使用onClick時,反應輸入數值不工作

<div> 
    <h4>Add A Player</h4> 
    <input 
    type="text" 
    placeholder="Enter a new name" 
    value={this.state.newPlayerName} 
    /> 
    <button onClick={this.handleAddPlayer}> 
    Press to Add Player 
    </button> 
</div> 

其中除名稱使用此功能的工作原理:

handleAddPlayer = e => { 
    const players = this.state.players.slice(0); 
    players.push({ 
    name: '', 
    id: getRandomInt(20, 55) 
    }); 
    this.setState({ 
    players: players, 
    newPlayerName: e.target.value 
    }); 
}; 

我想,當用戶輸入一個名稱,並將其提交獲取,它在更新函數更新數組(如果這是有道理的,道歉,因爲這對我來說仍然很新)。

在我的國家,我有:

this.state = { 
    id: players.id, 
    totalScore: 0, 
    countInfo: [], 
    evilName: '', 
    color: '#6E68C5', 
    scoreColor: '#74D8FF', 
    fontAwe: 'score-icon', 
    incrementcolor: '', 
    scoreNameColor: 'white', 
    glow: '', 
    buttonStyle: 'count-button-start', 
    newPlayerName: '', 
    players 
}; 

我不知道如何讓輸入要通過域名(或字符串)陣列,任何人都可以幫忙嗎?

回答

1

首先,您將綁定的輸入更新處理程序添加到錯誤的元素!您目前已將它連接到一個按鈕,您必須將它連接到輸入!一個onChange處理程序添加到您輸入的每一次更新值更改輸入:

<input 
    type="text" 
    placeholder="Enter a new name" 
    value={this.state.newPlayerName} 
    onChange={this.handleChange} 
/> 

然後創建處理變化的新方法:

handleChange = e => { 
    this.setState({ 
    newPlayerName: e.target.value 
    }); 
} 

這將讓陣營控制輸入,並將輸入值設置爲狀態,以便在添加新玩家時可以使用它。然後,設置處理程序以在點擊時添加新玩家。相反切片,推,重置,只需使用數組傳播語法:

handleAddPlayer = e => { 
    this.setState(prevState => ({ 
    players: [...prevState.players, { 
     name: this.state.newPlayerName 
     id: getRandomInt(20, 55) 
    }] 
    })); 
} 

這將設置players到以前的狀態的players財產name這就是輸入的值和一個隨機id新玩家對象。

相關問題