我可以在React Native上为this.props.children添加额外的回调吗?

时间:2017-12-09 19:31:07

标签: javascript reactjs react-native

让我们说这个.props.children [0]是来自父母的TouchableOpacity。

我想在这里添加额外的回调。我想要的是什么?我找不到任何解决办法。

感谢。

export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           //child is TouchableOpacity class in my code ***
           //I want to add LongPress callback by coding HERE. (like below)
           child.onLongPress = () => console.log('SUCESSS!!!'); //this code does not work.
           return child;
        }
        return {newchildren}
    }

1 个答案:

答案 0 :(得分:1)

使用React.cloneElement方法实现此目的

export default class NewClassXXX extends React.Component{

    render()
    {
        newchildren = React.Children.map(this.props.children, (child) => {
           return React.cloneElement(child, {onLongPress: () => console.log('SUCESSS!!!')})
        }
        return {newchildren}
    }