反应原生 :我们可以使用一些唯一 id 动态更新文本的值(不更新状态变量)



下面的代码可以通过按下按钮重新渲染来使用状态更改文本值很有用,但我想使用任何 id 更改相同文本的值,可以吗?

示例代码

import React, {Component} from 'react';
import {View, Text, Button} from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state = {
value:'Text Value To Be Change Without Updating State'
}
}
render(){
return(
<View style={{paddingTop: 20}}>
<Text style={{color: 'black'}}>{this.state.value}</Text>
<Button title="Click" onPress={this.onPressButton }/>
</View>
);
}
onPressButton = () => {
this.setState({
value: "Can we change value of same text using some unique id, as happens in android using findViewById"
})
}
}
}

感谢罗比的帮助,因为你为我提供了一个链接并解释了,一切都很完美。 示例代码:

clearText = () => {
this._textInput.setNativeProps({text: ''});
}
render() {
return (
<View style={{flex: 1}}>
<TextInput
ref={component => this._textInput = component}
style={{height: 50, flex: 1, marginHorizontal: 20, borderWidth: 1, borderColor: '#ccc'}}
/>
<TouchableOpacity onPress={this.clearText}>
<Text>Clear text</Text>
</TouchableOpacity>
</View>
);
} 

参考链接 - 直接操作

最新更新