绑定道具功能

时间:2019-06-21 15:27:34

标签: reactjs bind

我有两个React组件,Gallery和Image。图片组件使用Gallery函数作为道具。

我可以在没有箭头功能的情况下在渲染中进行调用吗?

图像组件:

class Image extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: 'none',
    };
  }

  render() {
    return (
      <div>
        <button className="image-icon" onClick={() => this.props.handleClone(this.props.i)} />
      </div>
    );
  }
}

图库组件:

class Gallery extends React.Component {
      constructor(props) {
        super(props);
        this.handleClone = this.handleClone.bind(this);
        this.state = {
          images: [],
        };
      }

      handleClone(i) {
        var newImages = this.state.images;
        newImages = newImages.slice(0, i + 1).concat(newImages.slice(i));
        this.setState({
          images: newImages,
        });
      }

      render() {
        return (
          <div>
            <div className="gallery-root">
              {this.state.images.map((dto, i) => {
                return <Image key={'image-' + dto.id + '-' + i} i={i} handleClone={this.handleClone} />;
              })}
            </div>
          </div>
        );
      }
    }

谢谢。

1 个答案:

答案 0 :(得分:3)

class Image extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      filter: 'none'
    };
  }

  handleClick = () => {
    this.props.handleClone(this.props.i);
  };

  render() {
    return (
        <div>
          <button className="image-icon" onClick={this.handleClick} />
        </div>
     );
   }
}