javascript - 如何将 props 传递给 React 组件中的状态

标签 javascript reactjs

我创建了这个组件,它使用对象数组并填充位于该状态的结果。它是一个根据存在的数据量显示箭头的轮播,所以这就是我通过状态来执行此操作的原因。 (我包含了整个代码,以便您可以看到)。

现在我希望这个轮播可以在不同的页面上使用,并且可以动态地从每个页面中提取数据。我知道我可以通过 Prop 来做到这一点,但我不确定如何重新组织当前组件才能做到这一点。

如何将数据传递到不同页面上的 props 并将其添加到此处的状态中?

class Carousel extends Component {
  constructor(props) {
      super(props);

      this.state = {
          items:  [
            {name: 'First Name', city: 'City'},
            {name: 'First Name2', city: 'City2'},
            {name: 'First Name3', city: 'City3'}
          ],
          active: 1,
          direction: ''
      };
      this.rightClick = this.moveRight.bind(this);
      this.leftClick = this.moveLeft.bind(this);
      this.setActive = this.setActive.bind(this);
  }

  renderSlides(item, index) {

      let position;
      const {active} = this.state;

      if (active === index) {
          position = `${styles.active}`;
      } else if (active === index + 1) {
          position = `${styles.prev}`;
      } else if (active === index - 1) {
          position = `${styles.next}`;
      } else if (active > index) {
          position = `${styles.left}`;
      } else if (active < index) {
          position = `${styles.right}`;
      }

    return (

             <div>
                    <div className={styles.SliderItem__name}>
                       - {item.name}, {item.city} {item.state}
                    </div>

             </div>
    );

  }

  renderSliderNav() {
      const slides = this.state.items;
      const active = this.state.active;

      return slides.map((slide, index) => (
          <a onClick={() => this.setActive(index)}
             key={index}
             className={classnames({[styles.active]: active === index})}>
            <li className={classnames(styles.LessonSlide__navDot, {[styles.active]: active === index})}></li>
          </a>
      ));
  };

  setActive(selected) {
      const direction = selected > this.state.active ? 'right' : 'left';

      this.setState({
          active: selected,
          direction: direction
      });
  }

  moveLeft() {
      const newActive = this.state.active - 1;

      if (this.state.active + 1 === 1) {
          return;
      }

      this.setState({
          active: newActive < 0 ? this.state.items.length - 1 : newActive,
          direction: 'left'
      });
  }

  moveRight() {
      const newActive = this.state.active;

      if (this.state.active + 1 === this.state.items.length) {
          return;
      }

      this.setState({
          active: (newActive + 1) % this.state.items.length,
          direction: 'right'
      });

  }


  render() {
      const items = this.state.items;

      if (!items || items.length === 0) {
          return null;
      }

      return (
          <div className={styles.LessonSlider}>
                <div className={styles.SliderItem__wrapper}>
                  <div className={styles.SliderItem__container}>
                    <h3>Results</h3>
                      <div className={`${styles.LessonSlider__container} ${styles.noselect}`}>
                          {this.state.active + 1 !== 1
                              && <button className={`${styles.LessonSlider__button} ${styles.LessonSlider__button__prev}`} onClick={this.leftClick} />}
                              {this.state.items.map((item, index) => this.renderSlides(item, index))}
                          {this.state.active + 1 !== this.state.items.length
                              && <div className={`${styles.LessonSlider__button} ${styles.LessonSlider__button__next}`}
                              onClick={this.rightClick} />}
                      </div>
                      <div>
                        <ul className={`${styles.LessonSlide__nav} ${styles.noselect} ${this.props.colourScheme}`}>
                          {this.renderSliderNav()}
                        </ul>
                      </div>

                  </div>
                </div>

          </div>
      );
  }
}

export default Carousel;

最佳答案

在我看来,您希望能够从像这样的其他页面调用Carousel

<Carousel items=[{name: 'First Name', city: 'City'}] />

您可以使用 props.itemsCarousel 中访问它

解决方案

constructor(props) {
    super(props);
    this.state = {
      items: props.items
    }
}

你也可以将所有的 props 放入这样的状态;但是,这可能会产生意想不到的后果,因此不建议这样做。

constructor(props) {
    super(props);
    this.state = {
      ...props
    }
}

文档

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

关于javascript - 如何将 props 传递给 React 组件中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734035/

相关文章:

javascript - 如何在不使用浏览器用户代理的情况下定位 iPad

javascript - react : How to pass an argument to a parent component

css - 带有圆 Angular 的 React 渐变 slider (评级组件)

javascript - 小屏幕的下拉菜单链接不好

javascript - 查询字符串 Javascript

javascript - 复制 "/"之后的 URL 并粘贴到按钮上

javascript - jquery qrcode 无法使用超过 34 个字符长

reactjs - 构建并部署后,Tailwind css 无法在 Vercel 上运行

reactjs - 当状态更新时,我们也想更新 React-Select 的 defaultValue

javascript - ES6中React类定义方法的两种方式有什么区别