I have some Credit Card-related TextInput
s in React Native. I want to collect these TextInputs in a separate Component.
So it looks something like
class CreditCard extends Component {
state = { number: null, expirationMonth: null, expirationYear: null, cvc: null };
render() {
return (
<View>
<TextInput onChangeText={...} ... />
<TextInput onChangeText={...} ... />
<TextInput onChangeText={...} ... />
</View>
);
}
}
and in my app, I am importing the Credit Card component and use it like
class AddCreditCard extends Component {
render() {
return (
<View>
<CreditCard ... />
<Button disabled={creditCardIsInvalid} ... />
</View>
);
}
}
I know how to save data in state in the Credit Card component, but how can I extract the data from the Credit Card component to the container component (AddCreditCard)?
I guess it's something like adding a creditCard
object to the container and an onChange
property to CreditCard
, so I can populate the creditCard object directly from the CreditCard
component?
You could move the state to the AddCreditCard
component and pass a prop to the CreditCard
component that will update the containers state. That way you can access the data in AddCreditCard
component via state
and via props
inside CreditCard
class AddCreditCard extends Component {
state = { number: null, expirationMonth: null, expirationYear: null, cvc: null };
textFieldChanged = (key, value) => {
let newState = {};
newState[key] = value;
this.setState(newState);
}
render() {
return (
<View>
<CreditCard
textFieldChanged={this.textFieldChanged}
number={this.state.number}
expirationMonth={this.state.expirationMonth}
expirationYear={this.state.expirationYear}
cvc={this.state.cvc}
/>
<Button disabled={creditCardIsInvalid} ... />
</View>
);
}
}
and then you can call it like this:
class CreditCard extends Component {
render() {
// this.props.number ...
return (
<View>
<TextInput
onChangeText={(text) => {
this.props.textFieldChanged('number', text)
}}
/>
<TextInput
onChangeText={(text) => {
this.props.textFieldChanged('expirationMonth', text)
}}
/>
<TextInput
onChangeText={(text) => {
this.props.textFieldChanged('expirationYear', text)
}}
/>
<TextInput
onChangeText={(text) => {
this.props.textFieldChanged('cvc', text)
}}
/>
</View>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.