Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.
- Use
React.setState()
to create adata
state variable and set its initial value equal to theoptions
prop. - Create a function
toggle
that is used to toggle thechecked
to update thedata
state variable and call theonChange
callback passed via the component’s props. - Render a
<ul>
element and useArray.prototype.map()
to map thedata
state variable to individual<li>
elements with<input>
elements as their children. - Each
<input>
element has thetype='checkbox'
attribute and is marked asreadOnly
, as its click events are handled by the parent<li>
element’sonClick
handler.
代码实现
const style = {
listContainer: {
listStyle: 'none',
paddingLeft: 0
},
itemStyle: {
cursor: 'pointer',
padding: 5
}
};
function MultiselectCheckbox({ options, onChange }) {
const [data, setData] = React.useState(options);
const toggle = item => {
data.forEach((_, key) => {
if (data[key].label === item.label) data[key].checked = !item.checked;
});
setData([...data]);
onChange(data);
};
return (
<ul style={style.listContainer}>
{data.map(item => {
return (
<li key={item.label} style={style.itemStyle} onClick={() => toggle(item)}>
<input readOnly type="checkbox" checked={item.checked || false} />
{item.label}
</li>
);
})}
</ul>
);
}
使用样例
const options = [{ label: 'Item One' }, { label: 'Item Two' }];
ReactDOM.render(
<MultiselectCheckbox
options={options}
onChange={data => {
console.log(data);
}}
/>,
document.getElementById('root')
);