将子事件暴露给父事件

The*_*n68 5 onclick event-handling react-native

我试图在 React Native 中处理父元素中按钮的子单击事件。我对本地反应很陌生,所以请原谅书中的任何错误:)

// my transparent button child

const styles = StyleSheet.create({
    button: {
        backgroundColor: 'transparent',
        borderColor: Theme.button.borderColor,
        borderWidth: Theme.button.borderWidth,
        borderRadius: Theme.button.buttonRadius,
        fontFamily: Theme.button.fontFamily,
        fontWeight: Theme.button.fontWeight,
        color: Theme.button.fontColor
    }
})

var handleClick = function() {
  console.log('You clicked: ');
}

const TransparentButton = React.createClass({
    render() {
        var boundClick = handleClick.bind(this);
        return (
            <Button
                style={styles.button}
                textStyle={styles.button}
                onPress={boundClick}>
                    {this.props.children}
                </Button>
        );
    }
});

module.exports = TransparentButton;

// and this is the snippent that is trying to catch the click event
class Welcome extends Component {
    render () {
        return (
            <Page
            style={styles.container}
            backgroundColor={Theme.bgColor}>

                <TransparentButton
                    handleClick={() => console.log('hello there outter')}>
                    Ryans Text Button
                </TransparentButton>
            </Page>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

内部事件点击记录正常,但外部事件从未发生。

atl*_*teh 2

那是因为在透明按钮中您没有调用父函数。

const TransparentButton = React.createClass({
    render() {
        return (
            <Button
                style={styles.button}
                textStyle={styles.button}
                onPress={this.props.handleClick}>
                    {this.props.children}
                </Button>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

es6 的方式几乎是相同的,最好在代码中保持一致,而不是混合 es5 和 es6:

export default TransparentButton extends Component{
    render() {
        return (
            <Button
                style={styles.button}
                textStyle={styles.button}
                onPress={this.props.handleClick}>
                    {this.props.children}
                </Button>
        );
    }
};
Run Code Online (Sandbox Code Playgroud)