我有一个包含文本元素的变量。此文本元素必须是一个变量,我需要更改显示的文本。这是我的代码:
import React, {Component} from 'react';
import { Button, Platform, StyleSheet, Text, View } from 'react-native';
type Props = {};
export default class App extends Component<Props> {
// Initializes testval and testItem.
constructor(props) {
super(props);
this.state = {
testval:0,
}
this.testItem =
<Text
style={{
position:'absolute',
left:50,
top:200,
backgroundColor:'white',
}}
>
Value: {this.state.testval}
</Text>
}
// Call `UpdateTest` after some time.
componentDidMount() {
setInterval(this.UpdateTest, 1000);
}
// Updates the test value.
UpdateTest = () => {
this.setState({
testval:this.state.testval+1,
});
}
// Renders the test items.
render() {
return (
<View style={styles.container}>
// Display the text item.
{this.testItem}
</View>
)
}
}
const styles = {
container: {
flex: 1,
backgroundColor: 'aqua',
}
}
将显示文本,但显示的testval
不会更改。谁能帮忙? 我需要知道如何在状态更改发生时使 RN 重新呈现变量中包含的文本元素。
注意:
在- 实际项目中,必须按照演示在构造函数中创建文本。
- 如果我将"渲染"中的"{this.testItem}"替换为它包含的
<Text>
块,那么我会看到testval
变化,但如前所述,我需要在变量中包含文本。
是否有理由无法在渲染中定义它将随着状态更改重新计算?
render() {
const { testVal } = this.state
testItem = (
<Text
style={{
position:'absolute',
left:50,
top:200,
backgroundColor:'white',
}}
>
Value: {testval}
</Text>
)
return (
<View style={styles.container}>
{testItem}
</View>
)
}
您可以使用componentDidUpdate
并重新分配testItem
的值。
constructor(props) {
super(props)
this.state = {
testval: 0
}
this.testItem = (
<Text
style={{
position: 'absolute',
left: 50,
top: 200,
backgroundColor: 'white'
}}
>
Value: {this.state.testval}
</Text>
)
}
componentDidUpdate() {
this.testItem = (
<Text
style={{
position: 'absolute',
left: 50,
top: 200,
backgroundColor: 'white'
}}
>
Value: {this.state.testval}
</Text>
)
}
componentDidMount() {
setInterval(this.updateTest, 1000)
}
updateTest = () => {
this.setState({ testval: this.state.testval + 1 })
}
render() {
return <View style={styles.container}>{this.testItem}</View>
}
好的,我明白这个问题了。创建testItem
时,将计算变量this.state.testval
。Text
元素包含此计算值,而不是变量。因此,更改变量不会执行任何操作。
为了解决这个问题,我创建了一个单独的类,该类具有一个用于设置变量值的函数和一个使用该值的render
函数。
class SuperText extends React.Component<Props> {
inval = 0;
constructor(props) {
super(props);
}
SetInval = (val) => {
this.inval = val;
}
render() {
return (
<Text
style={this.props.style}
>
Value: {this.inval}
</Text>
)
}
}
感谢所有提供帮助的人。