我试图处理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>
)
}
}
内部事件点击注册很好,但是外部事件永远不会发生。
答案 0 :(得分:2)
那是因为在TransparentButton中你没有调用父函数。
const TransparentButton = React.createClass({
render() {
return (
<Button
style={styles.button}
textStyle={styles.button}
onPress={this.props.handleClick}>
{this.props.children}
</Button>
);
}
});
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>
);
}
};