2016-12-22 46 views
4

我認爲一個例子最能說明我的問題。假設我有一個表格來選擇書籍和他們的頁面。用戶將有一個多選下拉菜單來選擇書籍。然後,從每本書中選擇,用戶可以選擇任意數量的頁面。最後,數據看起來像一個二維數組。頂層是所選書籍的排列,第二層是爲每本書選擇的頁面:多級選擇輸入

books: { 
    "Book 1": ["page1", "page2", "page3"], 
    "Book 2": ["page1", "page2"] 
} 

書籍的下拉將自動填充。加載時,下拉選擇書籍頁面的選項將被填充。

這是一個硬編碼的例子,是想看到基本的佈局:http://codepen.io/alanqthomas/pen/JbVGzW?editors=1000

我這樣做的反應。我無法想出一種方法來設置組件狀態中的這些值並動態顯示它們。我使用react-select作爲多選選擇輸入。

回答

1

當然。這是你想要的。當你想在書中嵌套頁面,那麼我所做的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> 
); 
+0

在什麼時候應該'addBook()'和'addPage()'叫?我希望頁面選擇輸入的選項對應於當前選定的書籍。 –

+0

@AlanThomas你已經有書籍數據,只是不知道如何動態顯示它?我已經更新了使用對象而不是嵌套數組的答案。每次賬面價值變化時,頁面都會重新呈現。 –

+0

這或多或少是我正在尋找的。我最終解決了我最初的問題。這讓我開始朝着正確的方向發展。 –