[英]get value from TextInput and pass to grandparent and to the child react native
我是新手,我的組件結構如下所示
MainScreen > LoginScreen > Form > UserInput
> ButtonSubmit
每個都是一個組件這是表單組件
export default class Form extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<KeyboardAvoidingView behavior="padding" style={styles.container}>
<UserInput
source={usernameImg}
placeholder="Username"
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
/>
<UserInput
source={passwordImg}
placeholder="Password"
returnKeyType={'done'}
autoCapitalize={'none'}
autoCorrect={false}
/>
</KeyboardAvoidingView>
);
}
}
這是UserInput組件,它以一種形式調用UserInput組件兩次,以獲取用戶名,以一種形式輸入密碼
export default class UserInput extends Component {
constructor(props){
super(props)
this.state = {
username: '',
Password:'',
};
}
render() {
return (
<View style={styles.inputWrapper}>
<Image source={this.props.source} style={styles.inlineImg} />
<TextInput
style={styles.input}
placeholder={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor="white"
underlineColorAndroid="transparent"
onChangeText={(username) => this.setState({ username})}
value={this.state.username}
/>
</View>
);
}
}
這是我擁有的loginScreen組件
export default class LoginScreen extends Component {
render() {
return (
<Form />
<ButtonSubmit />
);
}
}
這是我的MainScreen組件及其父對象
export default class Main extends Component {
render() {
return (
<Router>
<Scene key="root">
<Scene key="loginScreen"
component={LoginScreen}
animation='fade'
hideNavBar={true}
initial={true}
/>
</Scene>
</Router>
);
}
}
我需要從Form組件獲取2個字段的值,並且正在使用其子組件Userinput組件嗎? 我將為此使用的最佳解決方案是什么?
讓我們以父組件和一個子組件的簡單情況為例(假設它是一個輸入字段)。
您有兩種處理狀態的方法:
(1)父組件中的所有狀態。 父組件作為道具傳遞給子組件一個回調。 子組件中的輸入更改后,將調用回調。 由於它在父組件中,因此父組件可以更新狀態。
(2)使用redux存儲並從多個組件訪問它。
您可以使用redux來實現此目的,redux是javascript應用程序的可預測狀態容器,在redux中,我們可以為應用程序創建全局狀態並創建更改狀態的操作,可能需要花一些時間才能確定,但是知道redux的巨大好處。
在React中,除非明確允許,否則子組件無法將值發送回父組件。 您可以將回調傳遞給子組件並處理輸入。
要么
您可以做的是,如果將redux用於狀態管理,則可以使用redux-form 。
這是示例,將回調傳遞給子級
class Parent extends Component {
constructor() {
this.state = {
value: ''
};
}
//...
handleChangeValue = e => this.setState({value: e.target.value});
//...
render() {
return (
<Child
value={this.state.value}
onChangeValue={this.handleChangeValue}
/>
);
}
}
class Child extends Component {
//...
render() {
return (
<input
type="text"
value={this.props.value}
onChange={this.props.onChangeValue}
/>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.