【发布时间】:2021-06-03 04:51:53
【问题描述】:
您好,我是 React 和 typescript 的新手。我正在为复选框添加选中的属性,但发现它很棘手。我搜索了 SO,但仍然无法让它更接近工作。
这是我想要做的:
我正在使用单个子组件创建三个复选框组件[此处显示]。它们都有自己的值,我需要动态传递。
interface ItemProps {
readonly className?: string;
readonly checked: boolean | undefined;
readonly accentedUnchecked?: boolean;
readonly imageUrl: string;
readonly errorMessage?: string;
readonly statusChecked?: boolean | undefined;
readonly onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
readonly handleClick: (event: React.ChangeEvent<HTMLInputElement>) => void;
};
readonly hasError?: boolean;
readonly title?: string;
readonly value?: number;
readonly description?: React.ComponentType;
}
export class Item extends React.Component<
ItemProps,
{
readonly isExpanded: boolean;
readonly checkboxStatus: boolean;
readonly temp: boolean;
readonly checked: boolean;
}
> {
constructor(props) {
super(props);
this.state = {
isExpanded: false,
checkboxStatus: false,
temp: false,
checked: this.state.temp
};
this.handleClick = this.handleClick.bind(this);
this.onChange = this.onChange.bind(this);
}`
private onChange(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({ temp: e.currentTarget.checked });
}
private readonly handleClick = e =>
this.props.onChange({
currentTarget: { checked: e.currentTarget.checked }
} as any);
render() {
const unchecked = this.props.accentedUnchecked && this.props.checked === false;
return (
<label className="checkbox">
<input
type="checkbox"
checked={this.onChange} //Not working
onChange={this.props.onChange}
onClick={this.handleClick}
id={"test"}
data-id="0"
/>
);
问题是我不确定如何设置选中的属性,基于点击。当我使用
checked={this.props.checked}
我正在检查所有复选框。或者如果我使用
checked={this.handleClick}
我收到错误提示
不能在 typescript 中将 void 分配给布尔值。
任何有关如何解决此问题的建议都会非常有帮助
提前致谢
【问题讨论】:
标签: javascript reactjs events checkbox react-redux