亲爱的朋友,我正在尝试在react native组件中覆盖一个方法,请让我知道如何实现。
// BaseButton.js
import React, { Component } from 'react'
import { View, Button } from 'react-native'
export default class BaseButton extends Component {
onPress = () => {
console.log('Test')
}
render() {
return (
<View>
<Button
title="Press me"
disabled
onPress={() => this.onPress()}
/>
</View>
)
}
}
// HomeScreen.js
import React, { Component } from 'react'
import BaseButton from './Components/BaseButton'
BaseButton.prototype.onPress = () => {
console.log('Overrided...');
}
export default class HomeScreen extends Component {
render(){
return(
<BaseButton />
)
}
}
答案 0 :(得分:1)
据我所知,没有像组件覆盖这样的东西。但是,如果要自定义组件,则可以与另一个组件一起包装,并且可以使用props访问组件的默认功能,而对于其他功能,可以在包装器组件内部创建自己的状态和props。
请参考以下链接以了解有关反应本机道具的知识, https://reactnative.dev/docs/props
答案 1 :(得分:1)
您只需使用道具即可。
// BaseButton.js
import React, {Component} from 'react';
import {View, Button} from 'react-native';
export default class BaseButton extends Component {
onPress = () => {
console.log('Test');
};
render() {
return (
<View>
<Button
title="Press me"
disabled
onPress={this.props.onPress || this.onPress}
/>
</View>
);
}
}
// HomeScreen.js
import React, {Component} from 'react';
import BaseButton from './Components/BaseButton';
export default class HomeScreen extends Component {
render() {
return (
<BaseButton
onPress={() => {
console.log('Overrided...');
}}
/>
);
}
}