我不会在动态添加的输入中添加默认值。所以我想循环渲染裁判。我尝试过这样的事情
this.state.foods.forEach(el=> this[el.id] = React.createRef() )
但是它不起作用。任何想法动态呈现引用?我在构造函数内部运行此循环。
答案 0 :(得分:1)
您可以将每种食物作为字符串存储在数组中,而不是存储动态输入的引用,并在其对应的输入更改时更新字符串。这样,您只需要向数组添加一个空字符串即可添加新食物。
示例
class App extends React.Component {
state = {
foods: ["fish", "beef", "pasta"]
};
onChange = (index, food) => {
this.setState(prevState => {
const foods = [...prevState.foods];
foods[index] = food;
return { foods };
});
};
addFood = () => {
this.setState(({ foods }) => ({ foods: [...foods, ""] }));
};
render() {
return (
<div>
{this.state.foods.map((food, index) => (
<div>
<input
key={index}
value={food}
onChange={event => this.onChange(index, event.target.value)}
/>
</div>
))}
<button onClick={this.addFood}>Add food</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>