我很难在React中为单选按钮组件设置默认选项。
I'm having a surprisingly hard time setting a default option for a radio button component in React.
这是我的 RadioToggle 组件:
/** @jsx React.DOM */ var RadioToggle = React.createClass({ render: function () { var self = this; return ( <div className="RadioToggle"> {this.props.radioset.radios.map(function(radio, i){ return ( <label className="__option" key={i}> <h3 className="__header">{radio.label}</h3> {radio.checked ? <input className="__input" type="radio" name={self.props.radioset.name} value={radio.value} defaultChecked /> : <input className="__input" type="radio" name={self.props.radioset.name} value={radio.value} /> } <span className="__label"></span> </label> ) }) } </div> ); } }); module.exports = RadioToggle;以下是我创建组件的方式:
And here is how I'm creating the component:
<RadioToggle radioset={ { name: "permission_level", radios: [ { label: "Parent", value: 1, checked: false }, { label: "Child", value: 0, checked: true } ]} }/>以上代码有效,但我们不喜欢生成几乎相同的代码,具体取决于 radio.checked 选项。
The above code works, but we don't like generating almost identical code depending on the radio.checked option.
组件的设置方式,我传给它一个名称和一组无线电来创建,并且对于无线电阵列中的每个对象使用该数据来创建单选按钮。
The way the component is set up, I pass it a name and an array of radios to create, and for each object in the radios array use that data to create a radio button.
在其他情况下,我已经能够通过将三元语句设置为有条件地设置属性价值,如下所示,但这在这里不起作用。
In other cases I've been able to conditionally set attributes by putting ternary statements as the value, like below, but that doesn't work here.
的问题defaultChecked = {radio.checked? checked:} 即使输出变为 checked =checked一个单选按钮和检查另一方面,它默认选中了两个单选按钮,导致最后一个实际被检查。
The problem with defaultChecked={radio.checked ? "checked" : ""} is that even with the output becoming checked="checked" on one radio button and checked on the other, it makes both radio buttons checked by default, resulting in the last one actually being checked.
同样,上面的组件可以工作,但我希望有更多React经验的人会有更简洁的方法来做,而不是生成几乎相同的元素,除了那个属性。
Again, the component above works, but I'm hoping someone with some more experience with React will have a cleaner way of doing it rather than generating almost identical elements except for that attribute.
推荐答案checked / defaultChecked取布尔值,而不是字符串。
checked/defaultChecked take booleans, not strings.
<input className="__input" type="radio" name={self.props.radioset.name} value={radio.value} defaultChecked={radio.checked} />jsbin演示
附注:避免使用defaultChecked / defaultValue,而是使用onChange检查/值。
Side note: avoid defaultChecked/defaultValue and use checked/value with onChange instead.
更多推荐
在React.js中有条件地设置html属性
发布评论