【问题标题】:Creating dynamic radio buttons with React and Meteor and Simple Schema (using pup boilerplate)使用 React 和 Meteor 以及 Simple Schema 创建动态单选按钮(使用 pup 样板)
【发布时间】:2017-08-07 21:27:44
【问题描述】:

我是 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 事件处理程序不起作用,缺少什么?

注意:在网页上,我看到单选按钮在选择单选时发生变化,但新值没有保存。

【问题讨论】:

    标签: javascript reactjs meteor simple-schema


    【解决方案1】:
    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} />
      

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

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

    【讨论】:

    • 嗨 tomsp,我可以通过写 {Documents.schema.getAllowedValuesForKey('icon').map((el, i) =&gt; 完成问题 1,但保存新的 icon 字段仍然无法正常工作。 (我使用了你上面提到的箭头函数和onChange={this.handleRadioSelection}。有什么想法吗?
    • 您能否在 onChange 处理程序中添加 console.log(name, value) 以查看事件是否正确触发。
    • 好的,我找到了问题 2 的解决方案。不知道这是否是推荐的方法,但我已经测试过,它工作正常。在handleSubmit() 函数中,我将icon: this.icon.props.value 更改为icon: this.state.icon
    • 哈哈,伙计,你没有显示 submitHandler。所以状态设置很好,这意味着我的答案是正确的。请考虑接受它。
    • 当然,顺便说一句,任何想法如何显示检查的默认值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多