【发布时间】:2019-08-22 10:00:23
【问题描述】:
我需要从自定义组件获取数据到屏幕。首先我将数据传递给这个组件:
<SearchInputComponent dataFromParent={this.state.text} />
这是我的组件的代码:
class SearchInputComponent extends Component {
clearText = () => {
this._textInput.setNativeProps({ text: '' });
};
render() {
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
<Input
ref={component => this._textInput = component}
placeholder="Enter city"
value={this.props.dataFromParent}
/>
<Button
buttonStyle={{ width: 40, height: 40, backgroundColor: 'red' }}
onPress={this.clearText}
icon={(
<MaterialIcons
name="delete"
size={30}
color="black"
/>
)}
/>
</View>
);
}
}
export default SearchInputComponent;
据我了解,数据是从状态传递的,如果我在组件中更改它,它也会更改状态。或者也许我错了?但是当我尝试输入文本来输入这个组件时,它会立即清除。点击按钮后我需要获取文本(例如屏幕中的这种方法):
onPressSearch = () => {
Alert.alert(this.state.cityName);
};
那么,你能帮帮我吗?
UPD
class SearchInputComponent extends Component {
clearText = () => {
this._textInput.setNativeProps({ text: '' });
};
render() {
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
<Input
ref={component => this._textInput = component}
placeholder="Enter city"
onChangeText={this.props.onInputChange}
value={this.props.dataFromParent}
/>
<Button
buttonStyle={{ width: 40, height: 40, backgroundColor: 'red' }}
onPress={this.clearText}
icon={(
<MaterialIcons
name="delete"
size={30}
color="black"
/>
)}
/>
</View>
);
}
}
export default SearchInputComponent;
【问题讨论】:
标签: react-native react-component