简体   繁体   中英

How to pass props to a state in a React component

I have this component that I've created which uses an array of objects and populates results that are located in the state. It's a Carousel that displays arrows based on how much data is present, so that's why I'm doing this through state. (i'm including the entire code so you can see).

Now I want this Carousel to be used on different pages and the data to be pulled from each page dynamically. I understand that I can do this through props, but I'm not sure how to reorganize the current component to be able to do that.

How do I pass data into props on a different page and add it inside the state here?

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;

It sounds to me like you want to be able to call Carousel from other pages like this

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

Which you can access in Carousel with props.items

Solution

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

You could also put ALL your props into state like this; however, that can have unexpected consequences and is not recommended.

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

Documentation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM