通过React组件调用一个函数



没有呈现add函数。当单击呈现方法中的按钮时,函数内的文本不会出现。我觉得这也是与"这个"有关的问题之一,你们怎么看?

import {Button, StyleSheet, Text, View } from 'react-native'
import React from 'react'
export default class App extends React.Component
{
constructor() {
super()
}
add () {
return(
<Text>Hi</Text>
)}
render(){
return(
<View styles={styles.button}>
<Text> Set Timer </Text>
<Button onPress={this.add} title="Hey there"/>
</View>
)
}
}

const styles = StyleSheet.create({
button: {
width: 10,
height: 10,
}
});

如果您的目标是更改呈现方法的输出,那么这将不起作用。add函数的输出根本不会影响渲染方法——它会将JSX返回给按钮,而按钮不会对它做任何事情。

改变渲染方法输出的一种方法是让它依赖于内部状态。下面是一种常见的模式。我不确定你的用例是什么,因为这看起来像演示代码,但也许这个解决方案将为你工作。

constructor() {
super()
this.state = { add: false }
}
add() {
this.setState({ add: true });    
}
render() {
return(
<View styles={styles.button}>
{this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
<Button onPress={this.add} title="Hey there"/>
</View>
)
}

另一个注意事项是确保在构造函数中绑定函数,以便类知道通过'this'引用哪个函数。您也可以通过使用ES6函数来消除这些代码。在下面的例子。

使用<<p> em> :
constructor() {
super()
this.state = { add: false }
this.add = this.add.bind(this);
}
add() {
this.setState({ add: true });    
}
render() {
return(
<View styles={styles.button}>
{this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
<Button onPress={this.add} title="Hey there"/>
</View>
)
}

使用ES6函数:

constructor() {
super()
this.state = { add: false }
}
add = () => {
this.setState({ add: true });    
}
render() {
return(
<View styles={styles.button}>
{this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
<Button onPress={this.add} title="Hey there"/>
</View>
)
}

最新更新