找不到模块-更改图像

时间:2020-05-05 12:06:58

标签: javascript reactjs react-native

我想创建一个灵活的组件,如果将鼠标拖动到该组件上,它将改变图像。

import React, { Component } from "react";

export default class GitLogo extends React.Component {
    render() {
        return (
            <img src={require('../resources/GitHub-Mark-Light-32px.png')}
                 onMouseOver={e => (e.currentTarget.src = require('../resources/GitHub-Mark-32px.png'))}
                 onMouseOut={e => (e.currentTarget.src = require('../resources/GitHub-Mark-Light-32px.png'))}
            alt="Logo"/>
        );
    }
}

在这里一切正常。现在,我想使我的组件更加灵活,并允许他通过道具读取图像路径。

<GitLogo beforehover="../resources/GitHub-Mark-Light-32px.png" afterhover="../resources/GitHub-Mark-32px.png"/>
import React, { Component } from "react";

export default class GitLogo extends React.Component {
    render() {
        return (
            <img src={require('../resources/GitHub-Mark-Light-32px.png')}
                     onMouseOver={e => (e.currentTarget.src = require( this.props.afterhover ))}
                 onMouseOut={e => (e.currentTarget.src = require('../resources/GitHub-Mark-Light-32px.png'))}
            alt="Logo"/>
        );
    }
}

但是我总是出错:找不到模块'../resources/GitHub-Mark-32px.png' 最好的解决方案是什么?是require()功能不错,还是我应该使用其他方法?

1 个答案:

答案 0 :(得分:1)

图像需要首先加载,因此您需要在传递as道具时要求它们。将您的道具传递代码更改为以下内容...

<GitLogo beforehover={require("../resources/GitHub-Mark-Light-32px.png")} afterhover={require("../resources/GitHub-Mark-32px.png")}/>

然后像这样使用组件中的道具...

import React, { Component } from "react";

export default class GitLogo extends React.Component {
    render() {
        return (
            <img src={require('../resources/GitHub-Mark-Light-32px.png')}
                     onMouseOver={e => (e.currentTarget.src = this.props.afterhover)}
                 onMouseOut={e => (e.currentTarget.src = require('../resources/GitHub-Mark-Light-32px.png'))}
            alt="Logo"/>
        );
    }
}