2017-08-07 92 views
0

我是新來reactJS的,我正在學習如何使用單選按鈕使用pup樣板。使用React和Meteor和Simple Schema創建動態單選按鈕(使用pup樣板)

我想爲icon添加一個輸入無線電代碼/imports/ui/components/DocumentEditor/DocumentEditor.js,這是我在哪裏至今:

<FormGroup> 
    <ControlLabel>Icon</ControlLabel> 
    {['mobile', 'tablet', 'laptop', 'tv'].map((el, i) => 
    <Radio 
     ref={icon => (this.icon = icon)} 
     key={i} 
     name="icon" 
     value={el} 
     onChange={e => this.handleRadioSelection(e)} 
     inline> 
     <i className={`fa fa-3x fa-${el}`}></i> 
    </Radio> 
)} 
</FormGroup> 

處理程序:

handleRadioSelection (e) { 
    const { name, value } = e.target; 

    this.setState({ 
    [name]: value 
    }); 
} 

模式(使用simpl-schema

icon: { 
    type: String, 
    label: 'The icon that better represents the platform.', 
    allowedValues: ['mobile', 'tablet', 'laptop', 'tv'], 
}, 

我有2個問題:

  1. 我的數組是硬編碼的,我想從模式中導入allowedValues數組,如何操作?
  2. 我的onChange事件處理程序不起作用,缺少什麼?

注意:在網頁上,我看到單選按鈕在收音機選擇時發生變化,但新值不會被保存。

回答

2
  1. docs「您可以使用schema.getAllowedValuesForKey(key)得到允許值數組的關鍵。」

  2. 您需要將函數綁定到this上下文中。閱讀有關該主題的更多信息here。因此,簡而言之,無論是在構造函數中做this.handleRadioSelection = this.handleRadioSelection.bind(this);或使其箭頭功能:

    handleRadioSelection = (e) => { 
        const { name, value } = e.target; 
    
        this.setState({ 
        [name]: value 
        }); 
    } 
    

    ,並用它喜歡:

    <Radio onChange={this.handleRadioSelection} /> 
    

    對於箭頭功能正常工作,您需要添加通天插件用於轉換類屬性。做meteor npm install --save-dev babel-plugin-transform-class-properties並添加以下到您的.babelrc

    { 
        "plugins": ["transform-class-properties"] 
    } 
    
+0

嗨tomsp,我才得以完成的問題1,通過寫'{Documents.schema.getAllowedValuesForKey( '圖標')。圖(致發光(EL, (我使用了上面提到的箭頭函數和'onChange = {this.handleRadioSelection}'。任何想法? – w3jimmy

+0

你可以添加一個'console' .log(name,value)'到onChange處理程序來查看事件是否正確觸發 – tomsp

+0

好的,我找到了問題2的解決方案,不確定它是否是推薦的方式,但我已經測試過,並且工作正常。在'handleSubmit()'函數中,我已將'icon:this.icon.props.value'更改爲'icon:this.state .icon'! – w3jimmy