我想为用户创建的每个类别动态创建输入字段值,问题是我如何跟踪用户在输入字段中输入的内容。因为我无法创建 X 数量的状态,因为它是动态的。任何提示将不胜感激,我的代码如下所示:
var categories = newData.map((category,index) => {
console.log(category)
return (
<div className="content row marginCenter" key={category._id}>
<p>{category.category}</p>
<input type="text" /> //How do I keep track of what was entered for this input field??
<button onClick={() => this.addCategoryLink(category._id)}>Add
link</button>
</div>
)
})
最佳答案
I am wondering how to bind that to the button element
React 文档中有一节与这个问题的核心相关: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
假设您的状态包含一组“类别”对象 - 本质上,我认为您正在寻找的内容归结为您的 map 函数中的类似内容:
{this.state.categories.map(category => (
<input
type="text"
onChange={event => this.handleCategoryChange(category, event)}
value={category.value}
/>
)}
然后是一个看起来像这样的更改处理程序:
handleCategoryChange = (category, event) => {
const value = event.currentTarget.value;
this.setState(state => {
// Create a copy of the categories array:
const categories = [...state.categories];
// Create a copy of the category, with an updated value:
categories[category.index] = {
...category,
value
};
// Update state with the new values:
return { categories };
});
};
这是一个简单的演示: https://codesandbox.io/s/woqpwvl777
关于javascript - 动态添加输入字段并跟踪输入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354332/