[英]React Native Component - OnPress Function not working
我的問題是有關在導入的組件中添加帶有onPress
事件的按鈕。
因此,我建立了一個外部按鈕組件,該component.js
將從component.js
文件導入到app.js
。
export default class App extends Component {
{...}
render() {
return (
<Container style={{ backgroundColor: 'rgb(245, 247, 250)' }}>
{renderIf(display.beacon, <Beacon />)}
</Container>
);
}
}
此<Beacon />
組件顯示圖像和從另一個組件文件導入的兩個按鈕:
export class Beacon extends Component {
render() {
return (
<Grid>
<Row>
<Image
source={require("./scenerios/Welcome.png")}
style={styles.MainContainer}
/>
</Row>
<Row style={ {backgroundColor: Blue} } >
<ButtonWhite onPress={this._startScanning} name={"Start Scanning"} />
<ButtonWhite onPress={this._stopScanning} name={"Stop Scanning"} />
</Row>
</Grid>
);
}
}
當我在應用程序渲染中使用這些<ButtonWhite />
組件時,如下所示,它們可以正常工作:
export default class App extends Component {
{...}
render() {
return (
<Container style={{ backgroundColor: 'rgb(245, 247, 250)' }}>
<ButtonWhite onPress={this._startScanning} name={"Start Scanning"} />
<ButtonWhite onPress={this._stopScanning} name={"Stop Scanning"} />
</Container>
);
}
}
當我將它們移動到組件時,它們會顯示在屏幕上,但不會調用該函數。
避免打電話
this._stopScanning
移動組件后,您需要從組件中導入回調
import {_stopScanning} from <Component where you have the callbacks>
否則,您需要重構該組件,並在內部調用instad函數以將其作為道具接收
已解決-需要使用構造函數來引用該函數。
export class UnknownBeacon extends Component {
constructor(props) {
super(props);
this.state =
{
mainAppRef : props.mainAppRef
};
}
render() {
return (
<Grid>
<Row>
<Image
source={require("./scenerios/Welcome.png")}
style={styles.MainContainer}
/>
</Row>
<Row style={ {backgroundColor: tflBlue} } >
<TfLButtonWhite onPress={this.state.mainAppRef._startScanning} name={"Start Scanning"} />
<TfLButtonWhite onPress={this.state.mainAppRef._stopScanning} name={"Stop Scanning"} />
</Row>
</Grid>
);
}
}
如果這是渲染組件的位置:
{renderIf(display.beacon, <Beacon />)}
然后,您要將道具傳遞給組件:
{renderIf(display.beacon, <Beacon
startScanning={() => this._startScanning()}
stopScanning ={() => this._stopScanning()}
/>)}
在Beacon
組件中,您要調用道具:
export class Beacon extends Component {
render() {
return (
<Grid>
<Row>
<Image
source={require("./scenerios/Welcome.png")}
style={styles.MainContainer}
/>
</Row>
<Row style={ {backgroundColor: Blue} } >
<ButtonWhite onPress={this.props.startScanning} name={"Start Scanning"} />
<ButtonWhite onPress={this.props.stopScanning} name={"Stop Scanning"} />
</Row>
</Grid>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.