[英]React-Native: Access TextField value in another class
As an iOS dev I'm struggling a bit with react native. 作为一名iOS开发人员,我在本机反应方面有些挣扎。
I have two components inside different classes: 我在不同的类中有两个组件:
Component A is a view with a TextInput
组件A是带有TextInput
的视图
class A extends Component<Props>{
state = {
textFieldValue: ""
};
render() {
return (
<View>
<TextInput placeholder={this.props.placeholderText}
ref={textField => {
this.textField = textField;
}}
value={this.state.textFieldValue}
onChange={e => this.setState({ textFieldValue: e.target.value})}/>
</View>
);}
}
Component B uses A in it's view 组件B在其视图中使用A
class B extends Component<Props>{
render() {
return (
<View>
<A placeholder={"test"}/>
<TouchableOpacity onPress={() => {
//show text of input A here
}}>
<View>
<Text>{text}</Text>
</View>
</TouchableOpacity>
</View>
);}
}
How can I access the value/state with the value of the TextInput in A
from B
to show it on the button press? 如何从B
A
中使用TextInput的值访问值/状态以在按下按钮时显示它?
Try this on Class B 在B类上尝试
class B extends Component<Props>{
render() {
return (
<View>
<A placeholder={"test"} ref={c => this.textRef = c}/>
<TouchableOpacity onPress={() => {
//show text of input A here
alert(this.textRef.state.textFieldValue)
}}>
<View>
<Text>{text}</Text>
</View>
</TouchableOpacity>
</View>
);}
}
Access reference of class A through ref props, then get its own state. 通过ref道具访问A类的引用,然后获得其自己的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.