【发布时间】:2018-06-21 10:17:47
【问题描述】:
我准备了一个小演示:https://codepen.io/anon/pen/mKxPaB?editors=0010。
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
rows: [{ text: "first" }, { text: "second" }]
};
this.addNewRow = this.addNewRow.bind(this);
}
renderTableRow(t, index) {
return <Row key={index} {...t} />;
}
addNewRow() {
this.setState(prevState => {
const rowsCopy = prevState.rows.slice();
return { rows: [{ text: "NOTHING" }].concat(rowsCopy) };
});
}
render() {
return (
<div>
<table>
<tbody>
{this.state.rows.map((t, i) => this.renderTableRow(t, i))}
</tbody>
</table>
<button onClick={this.addNewRow}>Add new first row</button>
</div>
);
}
}
class Row extends React.Component {
constructor(props) {
super(props);
this.state = {
//it's not working either
//text: props.text
};
}
render() {
//if its "value" (instead of defaultValue), text area cannot be edited. When the onChange event is implemented, the same issue appears again
return (
<tr>
<td>
<textarea defaultValue={this.props.text} />
</td>
</tr>
);
}
}
// ========================================
ReactDOM.render(<List />, document.getElementById("root"));
我想动态地将行添加到应该可编辑的表的开头。在我看来,这个解决方案应该可以工作,但表格以错误的方式显示行值(最后一行文本重复,没有显示“NOTHING”文本)。使用“价值道具”+“onChange 事件”方法没有帮助。你能帮我解决这个问题吗? 谢谢!
【问题讨论】:
标签: reactjs