我如何默认检查反应中的单选按钮?

Mer*_*ero 2 radio-button reactjs map-function

我试图默认检查第一个单选按钮,以下代码可以帮助我做到这一点。加载页面时,会检查第一个单选按钮,但我面临的问题是它不允许我检查数组中也存在的其他按钮。

constructor(props: any) {
        super(props);
        this.state = {
            selectedSort: '',
            sort: ['Apple', 'Orange '],
        }
    }
this.state.sort.map((sortType:string, index:number) => {
     return <span key={`${sortType}${index}` onClick={() => this.setSort(sortType)} >
     <input type="radio" id={sortType} 
            value={this.state.selectedSort} 
           name={sortType} defaultChecked={index===0} 
           }/>
          <span>{sortType}</span>
                               
                                    })
 private setSort = (selectedSort: string) => {
        this.setState({
            selectedSort: selectedSort
        });
}
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 5

问题

defaultChecked值是一个布尔值,但您的条件sortType === 0将始终进行评估false,因为您sortType只是您的sort状态值之一,即["Apple", "Orange "]

解决方案

如果您希望默认选中第一个单选按钮,那么您应该与映射索引进行比较。

defaultChecked={index === 0}
Run Code Online (Sandbox Code Playgroud)

其他问题及建议

  1. 单选按钮组输入应全部具有相同的name属性。
  2. 使用语义label来包装您的输入,以便更容易访问。
  3. 使用无线电输入的onChange事件回调与onClick, 来更新状态。
  4. sortType对于 React 键来说,这些值本身就足够了。

代码:

{this.state.sort.map((sortType, index) => (
  <label key={sortType}>
    <input
      type="radio"
      id={sortType}
      value={selectedSort}
      name="sortType"
      defaultChecked={index === 0}
      onChange={(e) => this.setState({ selectedSort: e.target.id })}
    />
    {sortType}
  </label>
))}
Run Code Online (Sandbox Code Playgroud)

此外,我建议将其转换为完全受控的输入,因为您已经拥有它的所有部件。删除该value属性并使用checkedprop。设置您想要的初始检查状态。这将使您拥有已经有效的检查状态。

state = {
  selectedSort: 'Apple',
  sort: ['Apple', 'Orange '],
}

{this.state.sort.map((sortType, index) => (
  <label key={sortType}>
    <input
      type="radio"
      id={sortType}
      name="sortType"
      checked={sortType === this.state.selectedSort}
      onChange={(e) => this.setState({ selectedSort: e.target.id })}
    />
    {sortType}
  </label>
))}
Run Code Online (Sandbox Code Playgroud)

演示

编辑 how-i-default-check-a-radio-button-in-react