當然。這是你想要的。當你想在書中嵌套頁面,那麼我所做的setState將需要修改,但這是你的開始。
如果您需要幫助,只需詢問。
class Form extends React.Component {
constructor() {
super();
}
render() {
return (
<form>
<div>
<Books />
</div>
</form>
);
}
}
class Books extends React.Component {
constructor() {
super();
this.state = {
books: {
Book1: {
pages: [
{
text: Page 1,
value: Page1
},
{
text: Page 2,
value: Page2
}],
text: Book 1,
value: Book1
},
Book2: {
pages: [
{
text: Page 1,
value: Page1
},
{
text: Page 2,
value: Page2
}],
text: Book 2,
value: Book2
}
}
}
this.state.currentBookKey = this.state.books.Book1.value;
}
selectOnChange = (event) => {
this.setState((state) => ({ currentBookKey: event.target.value }))
}
render() {
return (
<div>
<label>Book</label>
<select multiple name="book" onChange={this.selectOnChange}>
{this.state.books.map(book => <Book value={book.value}}>{book.text}</Book>)}
</select>
<label>Pages to select</label>
<select multiple name="pages">
{this.state.books[this.state.currentBookKey].pages.map(page => <Page value={page.value}}>{page.text}</Page>)}
</select>
</div>
)
}
}
無狀態組件:
//React.children.only gives us an exception if more than one child
const Book = ({children, value}) => (
<option value={value}>{React.Children.only(children)}</option>
);
const Page = ({children, value}) => (
<option value={value}>{React.Children.only(children)}</option>
);
在什麼時候應該'addBook()'和'addPage()'叫?我希望頁面選擇輸入的選項對應於當前選定的書籍。 –
@AlanThomas你已經有書籍數據,只是不知道如何動態顯示它?我已經更新了使用對象而不是嵌套數組的答案。每次賬面價值變化時,頁面都會重新呈現。 –
這或多或少是我正在尋找的。我最終解決了我最初的問題。這讓我開始朝着正確的方向發展。 –