【问题标题】:Load Image in React native from props从 props 加载 React Native 中的图像
【发布时间】:2018-06-03 15:24:44
【问题描述】:

我正在尝试通过发送标题和图像 URL 来呈现来自基本组件的图像列表。

如果我像这样渲染图像,一切正常:

 <Image source={require('../assets/images/myImage.png')} />

当我尝试从道具渲染图像时,问题来了:

class ListItem extends Component {
    render() {
      return (
        <View>
          <Text>{this.props.title}<Text>
          <Image source={require(this.props.imageUri)} />
        </View>
      );
    }
};

ListItem.propTypes = {
  title: PropTypes.string.isRequired,
  imageUri: PropTypes.string.isRequired,
};

结果,我收到下一个错误:

require 的调用期望恰好有 1 个字符串文字参数,但这 已找到:require(this.props.imageUri)

我也尝试使用 uri 渲染图像

<Image source={{uri: this.props.imageUri}} />

package.js

"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",

【问题讨论】:

  • 你试过source={this.props.imageUri}吗? this.props.imageUri 的示例值是多少?您是在尝试使用相对路径还是绝对路径?
  • 检查stackoverflow.com/questions/36460827/…看看是否有帮助。
  • source={this.props.imageUri} - 是的,我试过了。我没有收到任何错误,但没有渲染图像。 this.props.imageUri = ../assets/images/myImage.png
  • And check stackoverflow.com/questions/36460827/… to see if it helps - 这无济于事,因为我不想将图像存储到state 中。大约有 100 种可能的图像组合在未来可能会发生变化。我正在寻找从 Json/APi 发送路径
  • 你不能写这样的动态 require 语句,它在错误中说,它想要一个字符串文字

标签: reactjs react-native


【解决方案1】:

如果您使用带有uri 的远程图像,它们可以是动态的,但对于本地图像,require 需要在构建时解析路径,因此它们不能。创建已知路径的哈希:

const imageNames = {
   apple: require('./images/apple.png'),
   orange: require('./images/orange.png'),
};

并用他们的名字来称呼他们:

class ListItem extends Component {
    render() {
      return (
        <View>
          <Text>{this.props.title}<Text>
          <Image source={imageNames[this.props.imageName]} />
        </View>
      );
    }
};

ListItem.propTypes = {
  title: PropTypes.string.isRequired,
  imageName: PropTypes.oneOf(Object.keys(imageNames)),
};

// e.g.
<ListItem imageName="orange" />

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2021-03-08
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多