简体   繁体   中英

How to pass onPress to props.children?

I'm trying to make a wrapper component in react-native<\/code> that I can pass down all its props to the children it wraps around. What I really want is to pass down all function props down to all its children. It looks something like this below. I want the onPress in Wrapper<\/code> to be called when the TouchableOpacity<\/code> is pressed.

const Wrapper = ({children,...props})=>{
      return <View {...props}>{children}</View>
}

const App = ()=>{
    return (
        <View style={{flex:1}}>
            <Wrapper onPress={()=>{console.log(2)}}>
                <TouchableOpacity/>
            </Wrapper>
        </View>
    )
}

It looks like you're looking to map<\/code> the children and apply the props to each one. That might look like this:

const Wrapper = ({children,...props})=>{
  return (<>
    {React.Children.map(children, child => (
      React.cloneElement(child, {...props})
    ))}
  </>);
}

const App = () => { return ( <View style={{ flex: 1 }}> <TouchableOpacity onPress={() => { \/\/ do the action need here here }}>

            <Wrapper  >
        </Wrapper>
    </TouchableOpacity>
        </View >
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM