【问题标题】:How to use delegate in React Native?如何在 React Native 中使用委托?
【发布时间】:2020-06-07 09:18:16
【问题描述】:

有没有一种方法可以像在 swift/ios 中一样在 react native 中进行委托。如果我们想将信息从父类传递给子类,我们可以通过传递 props 来实现。但是,如果我们想将一些信息从子类传递给父类怎么办。

PS:没有 Redux 或单例方法。

【问题讨论】:

    标签: ios swift react-native design-patterns delegation


    【解决方案1】:

    回调在 React 中很常见,可以用于这样的事情。

    // Child.js
    export default class Child extends Component {
    
        componentDidMount() {
            this.props.onEvent({ type : "event" });
        }
    
        render() {
            return (
                <Text>I'm a child</Text>
            );
        }
    }
    
    // Parent.js
    export default class Parent extends Component {
    
        const onChildEvent = (event) => {
            console.log(event); // { type : "event" }
        }
    
        render() {
            return (
                <Child onEvent={this.onChildEvent} />
            );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-07
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多