我试图寻找答案,但没有任何解决方法。正如您在代码中看到的那样,我正在使用require.context加载图像,但未加载。在以前的react js版本中,它曾经可以完美地工作。现在我正在使用React版本17.0.1。控制台中没有错误。如果导入图像并在src中使用它,则效果很好。我也试图用以前项目中使用的一些以前的图像来更改图像(使用React 16.xx版),这些图像在这里工作得很好。我正在使用npx-create-react-app创建反应应用程序。映像路径是正确的,如路径不正确“发生名为xxx的模块未找到错误”。当前行为:未显示图像,而是显示了alt值。预期的行为:应显示图片,而不显示alt值。
import React, { Component } from "react";
import commonStyles from "../css/common.module.css";
import loginStyles from "../css/login.module.css";
import { TextField, Button, Paper, Typography } from "@material-ui/core";
class Login extends Component {
state = {
userName: "",
password: "",
error: "",
};
render() {
const images = require.context("../images", true);
return (
<div
className={`${loginStyles.root} d-flex justify-content-center align-items-center ${commonStyles.bg}`}
>
<Paper
classes={{
root: `${commonStyles.paper} mt-2`,
}}
elevation={3}
>
<div className={`${loginStyles.child}`}>
<div className={`d-flex justify-content-center align-items-center`}>
<img
src={images(`./Shahmeer.png`)}
alt={`Shahmeer Avenue Logo`}
width="100"
height="100"
/>
</div>
<Typography
classes={{
root: `font-weight-bold`,
}}
variant="h5"
gutterBottom
>
Login
</Typography>
<form noValidate autoComplete="off">
<TextField
classes={{
root: `${commonStyles.textField}`,
}}
onChange={(e) => this.handleChange(e)}
id={"userName"}
label={"User Name"}
variant="outlined"
error={this.state.error ? true : false}
helperText={this.state.error}
value={this.state["userName"]}
/>
<TextField
classes={{
root: `${commonStyles.textField}`,
}}
onChange={(e) => this.handleChange(e)}
id={"password"}
label={"Password"}
variant="outlined"
error={this.state.error ? true : false}
helperText={this.state.error}
value={this.state["password"]}
/>
<div className={`w-100 d-flex justify-content-end mt-2`}>
<Button variant="contained" color="primary">
Login
</Button>
</div>
</form>
</div>
</Paper>
</div>
);
}
}
export default Login;
浏览器快照:在此处输入图像描述
您应该将default
属性用于图像:
<img
src={images(`./Shahmeer.png`).default}
alt={`Shahmeer Avenue Logo`}
width="100"
height="100"
/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句