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