[英]React - handle multiple toggle buttons (input type radio) with one function
I've got my custom icon toggle component: 我有我的自定义图标切换组件:
class ToggleIconSwitch extends Component {
render() {
const { leftIcon, rightIcon, name, handleOptionChange, checked, leftValue, rightValue } = this.props
return (
<div className="toggle-switch-icon-wrapper">
<div className="toggle-switch">
<input
type="radio"
name={ name }
id={ leftValue }
value={ leftValue }
checked={ checked === leftValue }
onChange={ handleOptionChange }
/>
<label htmlFor={ leftValue } className="icon">{ leftIcon }</label>
<input
type="radio"
name={ name }
id={ rightValue }
value={ rightValue }
checked={ checked === rightValue }
onChange={ handleOptionChange }
/>
<label htmlFor={ rightValue } className="icon">{ rightIcon }</label>
</div>
</div>
)
}
}
and then I've got multiple toggles on some page and I want to handle each toggle input change... 然后我在某个页面上有多个切换,我想处理每个切换输入更改...
_.map(acl, (permission) => {
return (
<div className="row" key={ permission.id } >
<ToggleIconSwitch
name={ _.toString(permission.id) }
leftIcon={ <VisibilityIcon className="svg" /> }
leftValue="read"
rightIcon={ <CreateIcon className="svg"/> }
rightValue="write"
checked={ permission.permission }
handleOptionChange={ this.toggleUsersPermission }
/>
<IconButton
aria-label="Delete"
className="icon-button animate"
onClick={ this.openDeleteDialog(permission) }
>
<CloseIcon className="icon-button-red" />
</IconButton>
</div>
)
})
The problem is that the toggleUsersPermission
function is always called only for the first ToggleIconSwitch
component, even if I click on another ToggleIconSwitch
. 问题是,即使我单击另一个ToggleIconSwitch
,始终仅对第一个ToggleIconSwitch
组件调用toggleUsersPermission
函数。 It also does not react when I click on the other toggle component's label, which is checked
in first toggle component in list. 当我单击另一个切换组件的标签时,它也没有反应,该标签在列表中的第一个切换组件中被checked
。 I'm always getting event.target
of the first toggle in list ... Why? 我总是得到列表中第一个切换的event.target
...为什么?
Try to click on the icons in CodeSandbox here 尝试在此处单击CodeSandbox中的图标
问题出在标签上,它们都具有相等的htmlFor
值,而且输入的id是相同的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.