首页 > 解决方案 > 绑定一个 props 函数

问题描述

我有两个 React 组件,Gallery 和 Image。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>
        );
      }
    }

谢谢。

标签: reactjsbind

解决方案


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>
     );
   }
}

推荐阅读