使用React和Meteor和Simple Schema创建动态单选按钮(使用pup样板)
问题描述:
我是新来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个问题:
- 我的数组是硬编码的,我想从模式中导入allowedValues数组,如何操作?
- 我的onChange事件处理程序不起作用,缺少什么?
注意:在网页上,我看到单选按钮在收音机选择时发生变化,但新值不会被保存。
答
从docs“您可以使用
schema.getAllowedValuesForKey(key)
得到允许值数组的关键。”-
您需要将函数绑定到
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"] }
嗨tomsp,我才得以完成的问题1,通过写'{Documents.schema.getAllowedValuesForKey( '图标')。图(致发光(EL, (我使用了上面提到的箭头函数和'onChange = {this.handleRadioSelection}'。任何想法? – w3jimmy
你可以添加一个'console' .log(name,value)'到onChange处理程序来查看事件是否正确触发 – tomsp
好的,我找到了问题2的解决方案,不确定它是否是推荐的方式,但我已经测试过,并且工作正常。在'handleSubmit()'函数中,我已将'icon:this.icon.props.value'更改为'icon:this.state .icon'! – w3jimmy