React:我可以向子级生成的 HTML 添加属性吗?

2023-12-27

我有一个包装其他组件的组件:

class MyComp extends React.Component {
  render() {
    return <div> {this.props.children} </div>
  }
}

假设我添加了另一个随机组件作为子组件:

<MyComp><FancyP>Hello</FancyP></MyComp>

最终的 HTML 将会是这样的:

<div>
  <p class="fancy">Hello</p>
</div>

我知道使用React.Children我可以向子组件添加新的 props,但我真正想做的是将自定义属性添加到任意随机子组件的生成 HTML 中,如下所示:

<MyComp childAttr={{'data-x':'value'}}><FancyP>Hello</FancyP></MyComp>

这将生成以下内容:

<div>
  <p class="fancy" data-x="value">Hello</p>
</div>         

有办法实现这一点吗?向子级添加道具不起作用,因为子级类不知道新道具并且忽略它们。


不知道为什么你需要这个,我建议你这样做在为时已晚之前重新思考您的架构.

但是你可以使用一些黑客技术ReactDOM.findDOMNode.

首先,您需要为每个子组件设置引用。通过克隆元素并分配引用。

然后将挂钩固定在上面componentDidMount and componentDidUpdate事件,使用查找 dom 元素findDOMNode并手动填充数据集。DEMO https://codepen.io/tarabyte/pen/ezBGoa.

import React, { Component, Children, cloneElement } from 'react'
import { render, findDOMNode } from 'react-dom'

class MyComp extends Component {
  componentDidMount() {
    this.setChildAttrs()
  }

  componentDidUpdate() {
    this.setChildAttr()
  }

  setChildAttrs() {
    const { childAttrs } = this.props
    const setAttrs = el => Object.keys(childAttrs)
      .forEach(attr => el.dataset[attr] = childAttrs[attr])

    // for each child ref find DOM node and set attrs
    Object.keys(this.refs).forEach(ref => setAttrs(findDOMNode(this.refs[ref])))
  }

  render() {
    const { children } = this.props
    return (<div> {
        Children.map(children, (child, idx) => {
          const ref = `child${idx}`
          return cloneElement(child, { ref });
      })} </div>)
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React:我可以向子级生成的 HTML 添加属性吗? 的相关文章

随机推荐