【问题标题】:map through nested children components in react通过嵌套子组件映射反应
【发布时间】:2017-09-23 06:01:16
【问题描述】:

我正在尝试向顶级组件中的嵌套子元素添加新属性。

我的更高级别的组件称为 Photo.js

import React, {Component} from 'react';
import PropTypes from 'prop-types';

export default class Photo extends Component{

  constructor(props){
    super(props);
    this.onHandleLoad = this.onHandleLoad.bind(this);

    this.state = {
      isLoaded:false
    }
  }

  onHandleLoad(event){
    this.setState({
      isLoaded:true
    })
  }

  render(){
    const {children} = this.props;
    return(
      <div className="photo-container">
        {children}
      </div>
    )
  }
}

这是我添加孩子的方法。

   <Photo >
      <Link to='/bla' className="slide-show-link">
        <img src={photo.photo} alt={`${photo.title} photo`}/>
      </Link>
    </Photo>

添加的孩子并不总是相同。有时它的嵌套层次可能更多,但它总是有一个 img 元素。 我想要一种能够映射所有嵌套元素并找到 img 元素并向其添加自定义道具的方法。

我要添加的道具是 onLoad={this.onHandleLoad) 所以它会在正确的范围内调用 Photo 内的 onHandleLoad。

我查看了 React.Children.map 但它只返回第一个元素而不是嵌套元素。 img 可能会下降 1 级或更多。 我怎样才能做到这一点。正在研究递归映射,但不确定那是要走的路。是否有一个内置的方法来处理这个?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    最好的方法可能是使用 redux 之类的东西,并为每个图像加载分派一个动作。但是,如果您当前不使用它,则需要进行大量重构。

    还有另一种非常适合这里的方式,那就是context。有many warnings about using context,但由于您只是提供回调,因此风险不大。

    上下文将允许您的父组件将回调传递任意数量的级别,而无需通过每个级别传递道具。

    -

    首先将childContextTypes 和getChildContext 添加到您的父组件:

    export default class Photo extends Component {
      static childContextTypes = {
        onHandleLoad: PropTypes.func
      };
    
      constructor(props) {
        super(props);
    
        this.state = {
          isLoaded: false
        }
      }
    
      getChildContext() {
        return {
          onHandleLoad: this.onHandleLoad
        };
      }
    
      onHandleLoad = (event) => {
        this.setState({
          isLoaded: true
        })
      }
    
      render() {
        const {children} = this.props;
        return(
          <div className="photo-container">
            {children}
          </div>
        )
      }
    }
    

    然后您将需要一个围绕您的&lt;img&gt;s 的子组件包装器,以使用contextTypes 挂钩到父上下文:

    class PhotoImage extends Component {
      static contextTypes = {
        onHandleLoad: PropTypes.func
      }
    
      static propTypes = {
        photo: PropTypes.string,
        title: PropTypes.string
      }
    
      render() {
        return (
          <img
            src={photo}
            alt={`${title} photo`}
            onLoad={this.context.onHandleLoad}
          />
        )
      }
    }
    

    【讨论】:

    • 哦,非常感谢。希望他们不会在接下来的几个版本中删除上下文。我一直远离它,但你是对的,这是最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2019-01-07
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-08-26
    • 2019-08-13
    相关资源
    最近更新 更多