在 React 中,我有一個列出資料行的表,每行都有一個按鈕,我想在它后面插入一行并添加允許用戶填寫通知資料并單擊保存然后洗掉表單行的組件。
這是我嘗試過的代碼。
addRow = (idx) => {
const table = document.getElementById("allocatorTable");
const row = table.insertRow(idx 1);
row.className = "editorRow";
const cell1 = row.insertCell(0);
cell1.colspan = "10";
cell1.appenChild(<TransactionRuleEditor />);
};
當然 <TransactionRuleEditor /> append 不起作用,但它讓您了解我想要實作的目標。
我還嘗試將表單添加到每一行并隱藏它們。但是當然你不能在一個頁面上有多個表單。
有什么想法嗎?馬爾科姆
uj5u.com熱心網友回復:
當您使用 React(或任何其他類似 MVC 的框架)時,您不會像那樣直接使用 DOM,您會采取不同的心態:您更改正在呈現的內容的狀態,然后框架進行呈現. 在這種情況下,您可能讓提供表格行的組件有一個狀態,當按鈕被按下時,它實際上提供了兩行(包裹在一個片段中)。
這是一個簡化的例子:
const {useState, Component} = React;
class Row extends Component {
constructor(props) {
super(props);
this.state = {
adding: false,
};
this.onAdd = this.onAdd.bind(this);
this.onDone = this.onDone.bind(this);
}
onAdd() {
this.setState({adding: true});
}
onDone() {
// (Obviously you'd do more here)
this.setState({adding: false});
}
render() {
const {adding} = this.state;
const {data} = this.props;
const row = <tr>
<td>{data.a}</td>
<td>{data.b}</td>
<td>{data.c}</td>
<td>{!adding &&
<input type="button" onClick={this.onAdd} value="Add" />
}</td>
</tr>;
if (!adding) {
return row;
}
return <React.Fragment>
{row}
<tr>
<td colSpan={3}>
The inputs go here.
</td>
<td>
<input type="button" onClick={this.onDone} value="Done" />
</td>
</tr>
</React.Fragment>;
}
}
// Or with hooks:
// const Row = ({data}) => {
// const [adding, setAdding] = useState(false);
// const row = <tr>
// <td>{data.a}</td>
// <td>{data.b}</td>
// <td>{data.c}</td>
// <td>{!adding &&
// <input type="button" onClick={() => setAdding(true)} value="Add" />
// }</td>
// </tr>;
// if (!adding) {
// return row;
// }
// // (You might memoize the callbacks via `useCallback`)
// return <React.Fragment>
// {row}
// <tr>
// <td colSpan={3}>
// The inputs go here.
// </td>
// <td>
// <input type="button" onClick={() => /* Obviously you'd do more here */ setAdding(false)} value="Done" />
// </td>
// </tr>
// </React.Fragment>;
// }
const Example = () => {
const [items] = useState([
{key: 1, a: "a1", b: "b1", c: "c1"},
{key: 2, a: "a2", b: "b2", c: "c2"},
{key: 3, a: "a3", b: "b3", c: "c3"},
]);
return <table>
<tbody>
{items.map(item => <Row key={item.key} data={item} />)}
</tbody>
</table>;
};
ReactDOM.render(<Example />, document.getElementById("root"));
td {
width: 70px;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
(使用該示例<React.Fragment>是因為 Stack Snippets 中的 Babel 版本非常過時,但在您的實際代碼中,您可以<>改用。)
當然,那只是草圖。但它讓您了解如何使用狀態來處理這種模式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359814.html
標籤:javascript html 反应
