【问题标题】:Is there a way to access 'this' children of the component in React?有没有办法在 React 中访问组件的“this”?
【发布时间】:2022-09-23 03:07:17
【问题描述】:

我正在使用类组件,我有一张主图片和一个来自数组的较小图片库。我对这些组件的结构是包含主图片和较小图片的所有图片容器,以及一个映射图库中图片的较小图片容器(每张图片都是另一个组件)。 我想在所有图片组件中添加一个状态,它处理主图片的变化,这样它就会得到点击的小图片的索引并将其传输到主图片,因此它会变成点击的图片。 当我正在使用类组件时,我正在使用 this.props,当我添加 handleClick 函数时,console.log(this.props) 显示 {productGal: Array(7)}。有什么办法可以得到“this”的点击子项?

我正在附加结构: 所有图片库

class ProductDetailPhotoGallery extends Component {
state ={
    imageSource: this.props.productGal[0]
} 

handlePictureChange = () => {
    console.log(this.props)
    this.setState({
    imageSource: this.props.productGal[3] //check if the picture changes
   })
}

render() {
    return (
        <ProductPhotoGalleryContainer>
            <ProductPageMiniatureImages 
            productGal={this.props.productGal}
            handlePictureChange={this.handlePictureChange}
            />
            <ProductPageDetailedImage 
            imageSrc={this.state.imageSource}
             />
        </ProductPhotoGalleryContainer>
    )
}

}

小图片容器

class ProductPageMiniatureImages extends Component {


render() {
    return (
        <ProductMiniatureImageContainer>
            {this.props.productGal.map((singlePrd, ind) => <ProductSmallImage 
            key={ind}
            id={ind}
            imageSrc={singlePrd} 
            imageAlt={\'Product image\'}
            handlePictureChange={this.props.handlePictureChange}
            />)}
        </ProductMiniatureImageContainer>
    )

小图片组件

class ProductSmallImage extends Component {

    render() {
        return (
            <>
                <SmallProductImage 
                onClick={this.props.handlePictureChange}
                src={this.props.imageSrc}
                alt={this.props.imageAlt}
                id={this.props.id}               
                />
            </>

        )
    }
}

    标签: javascript reactjs this


    【解决方案1】:

    最简洁的答案是不”。

    更长的解释: React 方法是单向数据流:从父级到子级,而不是相反。这种方法使您的应用程序代码更易于理解和维护。

    有几种方法可以在不同组件之间传递状态,最简单的一种是在第一个“父级”中创建状态,该状态位于层次结构树中所有相关子级之上,例如,如果我们希望状态可以从节点 1、6 和 7 - 我们应该在 3 处创建它:

    使用useState 钩子并将其传递给相关的孩子。

    还有其他传递上下文的方法,例如useContext hook 和 react-redux。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2022-10-07
      • 2021-03-19
      • 2014-12-22
      • 2018-08-12
      • 2023-03-30
      相关资源
      最近更新 更多