使用React和Meteor以及简单模式创建动态单选按钮(使用pup样板)

时间:2017-08-07 11:54:29

标签: javascript reactjs meteor simple-schema

我是新来的reactJS,我正在学习如何使用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'],
},

我有两个问题:

  1. 我的数组是硬编码的,我想从架构中导入allowedValues数组,怎么做?
  2. 我的onChange事件处理程序不起作用,缺少什么?
  3. 注意:在网页上,我看到收音机选择时单选按钮会发生变化,但新值不会被保存。

1 个答案:

答案 0 :(得分:2)

    来自docs
  1. 您可以使用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} />
    

    要使箭头函数起作用,您需要添加babel插件以转换类属性。执行meteor npm install --save-dev babel-plugin-transform-class-properties并将以下内容添加到.babelrc

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