因此,我想向附加到组件的任何子级添加某些样式.假设父组件被称为Section,子组件在本例中被称为Card.在Section.js年,我试着这样做:-

renderChildren = () =>{
  return React.Children.map(this.props.children, (child, i)=>{
    let el = React.cloneElement(child,{
      style: {opacity:0.5}
    })
    return el
  })
}

render(){
  <ScrollView>
       {this.renderChildren()}
   </ScrollView>
}

上述方法对我不适用.我想知道为什么.还有没有一种方法可以让我在子元素们之间绘制 map ,并将他们包装在一个新的组件中?像这样的;

this.props.children.map(Child => <Wrapper> <Child/> </Wrapper> )

推荐答案

要将子元素包装到包装器中,只需在包装器组件中调用React.Children.map即可:

const OpaqueWrapper = ({ children }) => (
    // check that children is defined 
    // if you do not want your wrapper to be rendered empty
    children && (
        <Wrapper>
            {React.Children.map(children, child => (
                React.cloneElement(child, {style: {...child.props.style, opacity: 0.5}})
            ))}
        </Wrapper>
    )
);

还请注意,必须将提供给原始子级的样式与注入的样式合并,否则将完全失go 为子级设置样式的能力.

See this codesandbox为例.

至于为什么它在你的代码中不起作用:你确定你的<Card>组件正确地处理了styleprops ,也就是说,将它应用于它的子组件吗?

EDIT:

Slootion将所有子组件包装在一个包装器中,但我

只需将包装器移动到React.Children.map:

const OpaqueWrapper = ({ children }) => (        
    React.Children.map(children, child => (
       <Wrapper>
           {React.cloneElement(child, {style: {...child.props.style, opacity: 0.5}})}
       </Wrapper>
    )))
);

React-native相关问答推荐

ReactNative如何在填充编辑表单 timeshift 除按钮禁用状态

Touchabble 不透明度不工作-react 本机

自定义单选按钮在react native 中不起作用

无法在 M1 zsh 上运行 adb segmentation fault adb

无法执行 JS 调用:__fbBatchedBridge 未定义

如何在 React Native 中正确地将组件导入到我的导航器中?

React Native 的 Firebase 初始错误(无法读取未定义的属性getItem)

在根项目ReactNativeStarter中找不到任务installRelease

react-native alignSelf 中心并拉伸到 maxWidth?

Error when running watchman

cmd : react-native run-android 在每次文件更改时

在react native 中出现Cannot read property 'pick算法rithm' of null错误

XCode AppIcon 基于方案

在 React Native 视图上强制 onLayout

如何在 React Native 中使用 index.js 而不是 (index.ios.js, index.android.js) 进行跨平台应用程序?

React Native:如何将 的高度和宽度设置为 容器?

如何在 React Native 中等待 Alert 对话框的响应?

Jest TransformIgnorePatterns 所有 node_modules 用于 React-Native Preset

xcode 使用错误的 node.js 版本

如何允许 react-native 启用对 JSX(扩展)文件的支持