我是 React 和 Typescript 的新手。在 AlertDismissable 类中,我正在设置请求完成时显示的属性。我使用了这个示例并对其进行了一些更改。
根据响应,我更改 AlertDismissable 的内容和样式。
当用户单击隐藏按钮时,我试图将其显示属性设置为 false。我已将状态与属性绑定,这就是我尝试设置道具的原因。但是,编译器抛出
TS2540:无法分配给“显示”,因为它是常量或只读属性。(handleDismiss 方法)
默认情况下,通用道具似乎是只读的。还有其他方法可以使它工作吗?
这是我的 AlertDismissable tsx
import * as React from 'react'
import { Alert, Button } from 'react-bootstrap';
interface AlertDismissableState {
show: boolean;
style: string;
}
export default class AlertDismissable extends React.Component<AlertDismissableState, AlertDismissableState> {
constructor(props: any, context: any) {
super(props, context);
this.handleDismiss = this.handleDismiss.bind(this);
this.handleShow = this.handleShow.bind(this);
this.state = {
show: this.props.show,
style: this.props.style
};
}
handleDismiss() {
this.props.show=false;
}
handleShow() {
this.props.show=true;
}
render() {
if (this.props.show && this.props.style == "Success") {
return (
<Alert bsStyle="success">
<p>
Ok
</p>
<Button onClick={this.handleDismiss}>Hide Alert</Button>
</Alert>
);
}
if (this.props.show && this.props.style == "Danger") {
return (
<Alert bsStyle="danger">
<p>
Failed
</p>
<Button onClick={this.handleDismiss}>Hide Alert</Button>
</Alert>
);
}
return (<div />);
}
}
这是我的包含 AlertDismissable 类的组件。为简洁起见,我删除了一些代码。
export default class UploadContainer extends React.Component<{}, UploadContainerState> {
uploadFile(event: any) {
fetch("ProposalData/UploadFile", {
...
})
.then(handleErrors)
.then(function (response) {
that.setState({ alertVisible: true, style: "Success" });
}).catch(function (error) {
that.setState({ alertVisible: true, style: "Danger" }); });
}
render() {
return (
<div>
<AlertDismissable show={this.state.alertVisible} style={this.state.style} />
</div>)}
打字稿:2.9.1
反应:“^16.4.0”
反应引导:“^0.32.1”
反应域:“^16.4.0”,