如何在 React JS 中将 import 作为 props 参数传递

How to pass import as props parameters in React JS

我使用 react-lotties,我想在许多 div 中添加不同的动画,仅更改 url 的 lotties

我是一个反应初学者,请善待:)

这是我的脚本:

    import React, { Component } from "react"
    import Lottie from "react-lottie"
    import animationData from "./lotties1.json"
    import animationData from "./lotties2.json"
    import animationData from "./lotties3.json"
    import "./lotties.css"

    class LottiesC extends Component {
      render() {
        const defaultOptions = {
          loop: true,
          autoplay: true,
          animationData: animationData,
          rendererSettings: {
            preserveAspectRatio: "xMidYMid slice",
          },
        }

        return (
          <div className="x">
            <Lottie options={defaultOptions} height={600} width={600} />
          </div>
        )
      }
    }

    export default LottiesC

-我的index.js组件:


       import React from "react"
        import Navigation from "../components/Navigation"
        import LottieControl from "../components/LottiesC"

        const index = () => {
          return (
            <section className="index">
              <div><LottiesC animationData ={lotties 1}  /> </div>
               <div><LottiesC  animationData ={lotties 2} /> </div>
              <div><LottiesC animationData ={lotties 3}  /> </div>
            </section>
          )
        }

        export default index

正如@Dellirium 已经提到的,你应该通过 props 将不同的值传递给你的组件。

工作原理如下:

const animationDatas = [
  { id: 'first' },
  { id: 'second' },
  { id: 'third' },
];

class LottiesC extends React.Component {
  render() {
    const defaultOptions = {
      // loop: true,
      // autoplay: true,
      animationData: this.props.animationData,
      // rendererSettings: {
      //  preserveAspectRatio: "xMidYMid slice",
      // },
    }

    return (
      <div className="x">
        {/** <Lottie options={defaultOptions} height={600} width={600} /> **/}
        {JSON.stringify(defaultOptions)}
      </div>
    )
  }
}

const App = () => {
  return (
    <section className="index">
      <div><LottiesC animationData={animationDatas[0]}  /></div>
       <div><LottiesC  animationData={animationDatas[1]} /></div>
      <div><LottiesC animationData={animationDatas[2]} /></div>
    </section>
  )
}

ReactDOM.render(<App />, document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>