如何在React Native中使用委托

时间:2020-02-23 16:04:11

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

是否有一种方法可以像在swift / ios中一样委派响应本机。如果我们想将信息从父类传递给子类,我们可以通过传递道具来实现。但是,如果我们想将某些信息从子类传递到父类,该怎么办?

PS:没有Redux或单例方法。

1 个答案:

答案 0 :(得分:0)

回调在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} />
        );
    }
}