首页 > 解决方案 > 从子组件更改父组件中的数组

问题描述

我有一个名为的父组件Gallery和一个名为image. 另外,我有一个克隆按钮,按下它,这个图像应该被复制到 Gallery 组件中的图像数组中。

图像渲染

画廊中的 setState

画廊渲染

问题是它向数组中添加了一个未定义的项目而不是副本。

谢谢你帮助我:)

class Image extends React.Component {
  static propTypes = {
    dto         : PropTypes.object,
    galleryWidth: PropTypes.number,
  };

  constructor(props) {
    super(props);
    this.filters = ``['blur(3px)', 'brightness(200%)'
      , 'contrast(150%)', 'grayscale(50%)', 'opacity(30%)'];
    this.calcImageSize = this.calcImageSize.bind(this);
    this.state = {
      size  : 200,
      filter: 'none',
      extend: false,
    };
  }

  calcImageSize() {
    const { galleryWidth } = this.props;
    const targetSize = 200;
    const imagesPerRow = Math.round(galleryWidth / targetSize);
    const size = (galleryWidth / imagesPerRow);
    this.setState({
      size,
    });
  }

  componentDidMount() {
    this.calcImageSize();
  }

  toggleFilter = () => {
    const i = Math.floor(Math.random() * 5);
    this.setState({ filter: this.filters[i] });
  };

  // toggleClone = () => {
  //     this.props.cloneImage(this)
  // }

  urlFromDto(dto) {
    return `https://farm${dto.farm}.staticflickr.com/
    ${dto.server}/${dto.id}_${dto.secret}.jpg`;
  }

  renderImg() {
    console.log('im rending again');
    return <div
      className="image-root"
      style={{
        backgroundImage: `url(${this.urlFromDto(this.props.dto)})`,
        width          : this.state.size + 'px',
        height         : this.state.size + 'px',
        filter         : this.state.filter,
        marginLeft     : '35%',
      }}
    ></div>;
  }

  onDismiss = () => {
    this.setState({ extend: false });
  };

  enter;
  code;
  here;

  render() {
    if (!this.state.extend)
      return (
        <div
          className="image-root"
          style={{
            backgroundImage: `url(${this.urlFromDto(this.props.dto)})`,
            width          : this.state.size + 'px',
            height         : this.state.size + 'px',
            filter         : this.state.filter,
          }}
        >
          <div>
            <FontAwesome
              className="image-icon" name="clone" title="clone"
              onClick={() => this.props.cloneImage(this)}
            />
            <FontAwesome
              className="image-icon"
              name="filter"
              title="filter"
              onClick={this.toggleFilter}
            />
            <FontAwesome
              className="image-icon"
              name="expand"
              title="expand"
              onClick={() => this.setState({ extend: true })}
            />
          </div>
        </div>);
    else
      return <ImageView img={this.renderImg()} onDismiss={this.onDismiss}>
      </ImageView>;

  }
}

export default Image;

标签: reactjs

解决方案


推荐阅读