我正在创建一个预览模式,以查看单击时的特定图像。我的想法是将状态属性设置为null,然后单击图像,然后将状态设置为特定文件,并将图像路径呈现为图像源。但是,打字稿不喜欢这样,并指出Object is possibly null
。
selectedFile: Asset
,但是在父组件中出现错误,希望它将文件传递给下级。我不希望它具有这种行为。selectedFile: Asset<{}>()
,但是Typescript抱怨我将其用作类型而不是值。import * as React from "react"
import { Company } from "data/companies"
import { Asset } from "data/companies"
import Modal from "components/Modal"
interface MediaLibraryProps {
company: Company
}
class MediaLibrary extends React.Component<MediaLibraryProps> {
state = {
mediaLibrary: [],
editModalIsOpen: false,
selectedFile: null
}
toggleEditModal = () => {
this.setState({ editModalIsOpen: !this.state.editModalIsOpen })
}
openEditModal = (file: Asset) => {
this.setState({
editModalIsOpen: true,
selectedFile: file
})
}
getMediaLibrary = async () => {
await fetch(
`${process.env.REACT_APP_SA_API_URL}/${this.props.company.id}/images`,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
).then(blob => blob.json())
.then(function (data: any) {
return data.map((file: Asset) => Object.assign(file, {
assetId: file.assetId,
path: file.path
}))
}).then((data) => this.setState({ mediaLibrary: [...data] }))
}
render() {
const files = this.state.mediaLibrary.map((file: Asset) => (
<div key={file.assetId} onClick={() => this.openEditModal(file)}>
<div>
<img src={`${process.env.REACT_APP_SA_CDN_URL}${file.path}`} />
</div>
</div>
))
return (
<div>
<div>
<h2>Media Library</h2>
</div>
{files}
<hr />
<Modal isOpen={this.state.editModalIsOpen} toggleOpenness=
{this.toggleEditModal}>
<img
src={this.state.selectedFile.path}
onClick={this.toggleEditModal}
/>
</Modal>
</div>
)
}
}
export default MediaLibrary
答案 0 :(得分:0)
我敢肯定有一种更干净的方法可以做到这一点,但是我通过设置来解决了
state = {
selectedFile: {
path: ""
}
}
openEditModal = (file: Asset) => {
this.setState({
editModalIsOpen: true,
selectedFile: {
path: file.path
}
})
}