【问题标题】:React Native: How can i put variable inside require without giving me an errorReact Native:如何将变量放入 require 而不给我一个错误
【发布时间】:2018-10-21 06:05:24
【问题描述】:

这是我得到的错误:

calls to `require` expect exactly 1 string literal argument, but this was found: `require(image.path)`

这是我的代码:

class NewPost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uploadPicture: null
        }
    }

  openGallery() {
        ImagePicker.openPicker({
            width: 600,
            height: 400,
            cropping: true
        }).then(image => {
            uploadPictureVar = require(image.path);
            this.setState({ uploadPicture: uploadPictureVar });
        });
    }
}

render() {
  return (
  <View style={styles.imageContainer}>
      {this.state.uploadPicture ?
         <Image
             style={styles.imagePost}
             source={this.state.uploadPicture}
         />
        : null}
   </View>
  )
}

我看到这个问题require() must have a single string literal argument React Native 但是我没有字符串可以放入我上传图片时得到的要求中。

【问题讨论】:

标签: reactjs react-native


【解决方案1】:

如果你真的需要将它与变量一起使用,也许你可以试试这个技巧:

uploadPictureVar = require("" + image.path);

uploadPictureVar = require(`${image.path}`);

【讨论】:

  • @FrancoCoronel,我不知道真正的问题是什么,但它应该适用于我认为的require 部分。这是一个工作示例:codesandbox.io/s/oo1m6nnp06
猜你喜欢
  • 2018-10-31
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
相关资源
最近更新 更多