是否可以为props.children添加无ref引用?

4
这里是一个例子...
<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}

需要在 ChildItem.js 中使用元素引用 element ref 来执行一些逻辑,而不必从 App.js 传递它到每个元素中。

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

注意: 我不想从 App.js 添加任何引用

如果有办法操作 props.children 或克隆,然后添加 ref ,那么这个解决方案对我来说是可以的

有什么提示吗?


这很容易直接实现。你可能正在寻找这个:https://reactjs.org/docs/forwarding-refs.html - Ashish
我不希望从 App.js 中添加任何引用。 - Mohamed Abu Galala
为什么你会使用引用来做这样的事情呢?不仅可以得到样式解决方案,还可以在React中使用高级API,例如cloneElement。 - Dennis Vash
我可以尝试克隆整个props.children并对其进行操作。 - Mohamed Abu Galala
我正在开发一个包装组件,可以突出显示其子元素中的每个更改,但是必须将ref传递给每个子元素才能突出显示它。 在每个元素上传递ref非常麻烦,我想从包装器中创建它。这里有一个演示。 http://react-change-highlight.surge.sh/ - Mohamed Abu Galala
2个回答

2
我建议查看styled-components并创建一个能够接受props的样式化p。这样,您就可以使用条件来更改样式。
const Paragraph = styled.p`
  background-color: ${props => props.someVar === 'someValue' ? '#fff' : '#000'};
`

我想从 Wrapper.js 而不是 App.js 中进行操作。 - Mohamed Abu Galala

1
也许这对你有用:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接