React实现下拉选择动态生成指定数量输入框并支持删除
Hey there! Great job getting the manual add/remove functionality working—you're already halfway there. Let's adjust your code to let a dropdown selection control the number of input groups, while keeping the ability to remove individual groups manually. Here's how to do it:
Step-by-Step Modifications & Full Code
First, we'll add a dropdown to select the number of input groups, tie it to your component state, and update the users array whenever the dropdown selection changes. We'll also make sure existing input values are preserved when adjusting the count.
class App extends React.Component { constructor(props) { super(props); // Add selectedCount to track dropdown value, start with 1 this.state = { users: [{firstName: "", lastName: ""}], selectedCount: 1 }; this.handleSubmit = this.handleSubmit.bind(this); this.handleCountChange = this.handleCountChange.bind(this); } // Handle dropdown selection change handleCountChange(e) { const newCount = parseInt(e.target.value); const currentUsers = [...this.state.users]; if (newCount > currentUsers.length) { // Add empty user objects to reach the new count const usersToAdd = newCount - currentUsers.length; for (let i = 0; i < usersToAdd; i++) { currentUsers.push({ firstName: "", lastName: "" }); } } else if (newCount < currentUsers.length) { // Trim the array to the new count (preserves first N entries) currentUsers.splice(newCount); } this.setState({ users: currentUsers, selectedCount: newCount }); } addClick(){ this.setState(prevState => ({ users: [...prevState.users, { firstName: "", lastName: "" }], // Update selectedCount when manually adding selectedCount: prevState.selectedCount + 1 })) } createUI(){ return this.state.users.map((el, i) => ( <div key={i}> <input placeholder="First Name" name="firstName" value={el.firstName ||''} onChange={this.handleChange.bind(this, i)} /> <input placeholder="Last Name" name="lastName" value={el.lastName ||''} onChange={this.handleChange.bind(this, i)} /> <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/> </div> )) } handleChange(i, e) { const { name, value } = e.target; let users = [...this.state.users]; users[i] = {...users[i], [name]: value}; this.setState({ users }); } removeClick(i){ let users = [...this.state.users]; users.splice(i, 1); this.setState({ users, // Update selectedCount when manually removing selectedCount: users.length }); } handleSubmit(event) { alert('A name was submitted: ' + JSON.stringify(this.state.users)); event.preventDefault(); } render() { // Generate dropdown options (1 to 10 here—adjust max as needed) const dropdownOptions = []; for (let i = 1; i <= 10; i++) { dropdownOptions.push( <option key={i} value={i}>{i}</option> ); } return ( <form onSubmit={this.handleSubmit}> {/* Add the dropdown selector */} <div> <label>Number of users: </label> <select value={this.state.selectedCount} onChange={this.handleCountChange} > {dropdownOptions} </select> </div> {this.createUI()} <input type='button' value='add more' onClick={this.addClick.bind(this)}/> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render(<App />, document.getElementById('container'));
Key Changes Explained
- Added
selectedCountstate: Tracks the number selected in the dropdown, so we can keep the dropdown in sync with the actual number of input groups. - Dropdown component: Renders options from 1 to 10 (you can change the max value in the loop to fit your
nrequirement). It's bound toselectedCountso the selection stays in sync when users add/remove manually. handleCountChangemethod: Adjusts theusersarray based on the new selected count:- If the new count is higher than current, adds empty user objects to reach the target number.
- If lower, trims the array to the new count (preserving the first N entries' input values).
- Sync
selectedCounton manual add/remove: When users click "add more" or "remove", we updateselectedCountto match the new length ofusers, so the dropdown always shows the correct current number of groups.
This way, users can either pick a number from the dropdown to set the exact number of input groups, or manually add/remove groups—and the dropdown will update to reflect the current count either way.
内容的提问来源于stack exchange,提问作者Aniket Yadav

