【问题标题】:Is it possible to add ref of props.children have no ref是否可以添加 props.children 的参考没有参考
【发布时间】:2019-11-04 17:22:00
【问题描述】:

这里是一个例子...

App.js

<Wrapper>
        <p ref={React.createRef()}>{state.result2}</p>
        <p>{state.result2}</p>
        <p>{state.result3}</p>
        <p>{state.result4}</p>
</Wrapper>

Wrapper.js

{props.children.map((child, idx) => (
        <ChildItem
          key={idx}
          {...props}
          child={child}
        ></ChildItem>
))}

 {props.children}

并且能够使用 element refChildItem.js 中执行一些逻辑,而无需在 App.js 的每个元素中传递它。

EX,我想在一些逻辑检查后更改任何元素的背景 所以,我可以换props.child.ref.current.style.background = '#fff';

注意:我不想添加来自App.js的任何引用

如果有任何方法可以操作 props.children 或克隆然后添加 ref 这个解决方案对我来说没问题

有什么提示吗?

【问题讨论】:

  • 这是直接可能的。你可能正在寻找这个reactjs.org/docs/forwarding-refs.html
  • 我不想添加来自App.js的任何引用
  • 你为什么要参考参考做这样的事情?您不仅拥有样式解决方案,而且还拥有像 cloneElement 这样的高级 API。
  • 我可能会尝试克隆整个 props.children 的元素并对其进行操作。
  • 我正在开发一个包装器组件,它可以突出显示其子项中的每个更改,但我必须向每个子项传递一个 ref 以便能够突出显示它。在每个元素上传递该 ref 非常烦人,我想从包装器中创建它。这是一个演示。 react-change-highlight.surge.sh

标签: javascript reactjs


【解决方案1】:

我建议查看styled-components 并制作一个可以带道具的样式p。这样您就可以使用条件更改样式。

const Paragraph = styled.p`
  background-color: ${props => props.someVar === 'someValue' ? '#fff' : '#000'};
`

【讨论】:

  • 我想从Wrapper.js 而不是App.js 操作它
【解决方案2】:

也许这对你有用:

import React, { Component } from 'react'

export class Wrapper extends Component {
  render () {
    const { children } = this.props
    const childrenWithRefs = React.Children.map(children, child => {
      // use child.props here ...

      return React.cloneElement(child, { ref: React.createRef() })
    })

    return (
      <div>
        {childrenWithRefs}
      </div>
    )
  }
}

export default Wrapper

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 1970-01-01
    • 2013-06-05
    • 2018-02-13
    • 1970-01-01
    • 2012-12-23
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多