in my react native project I`ve created a custom input component, let's call it "CustomInput". This just returns a standard .
const CustomInput = (props) => {
return (
<TextInput
style={{
backgroundColor: "white",
padding: 10,
borderWidth: 1,
borderColor: "#eee",
borderRadius: 2,
marginBottom: 12,
}}
placeholder={props.placeholder}
value={props.value}
></TextInput>
);
};
I want to call it in a parent component, like:
<CustomInput
placeholder="Family Name"
value={this.state.familyName}
onChangeText={(text) => this.setState({ familyName: text })}
/>;
How can I dynamically use the onFocus() and onBlur() method to highlight them when the user-focused it?
If I don't use a custom input I can do it like that:
<TextInput
ref={(input) => {
this.inputFullName = input;
}}
style={styles.loginTextInput}
placeholder="Fullname"
value={this.state.fullName}
onChangeText={(text) => this.setState({ fullName: text })}
onFocus={() => this.focusedInput(this.inputFullName)}
onBlur={() => this.blurInput(this.inputFullName)}
/>;
focusedInput = (inputField) => {
inputField.setNativeProps({
style: { borderColor: "#4094ec" },
});
};
CodePudding user response:
The Solutions is a mix up, between forwarding the ref and passing the function:
const CustomInput = React.forwardRef((props, ref) => (
<TextInput
ref={ref}
style={{
backgroundColor: "white",
padding: 10,
borderWidth: 1,
borderColor: "#eee",
borderRadius: 2,
marginBottom: 12,
}}
onChangeText={props.onChangeText}
placeholder={props.placeholder}
value={props.value}
onFocus={props.onFocus}
onBlur={props.onBlur}
></TextInput>
));
Call in the parent component:
<CustomInput
ref={(input) => {
this.inputLastName = input;
}}
placeholder={i18n.t("enterLastName")}
value={this.state.familyName}
onChangeText={(text) => this.setState({ familyName: text })}
onFocus={() => this.focusedInput(this.inputLastName)}
onBlur={() => this.blurInput(this.inputLastName)}
/>
CodePudding user response:
You can add them in props:
const CustomInput = (props) => {
return (
<TextInput
style={{
backgroundColor: "white",
padding: 10,
borderWidth: 1,
borderColor: "#eee",
borderRadius: 2,
marginBottom: 12,
}}
placeholder={props.placeholder}
value={props.value}
onFocus={() => props.onFocus()}
onBlur={() => props.onBlur()}
></TextInput>
);
};
And call it like:
<CustomInput
placeholder="Family Name"
value={this.state.familyName}
onChangeText={(text) => this.setState({ familyName: text })}
onFocus={() => yourFunctionForOnFocus()}
onBlur={() => yourFunctionForOnBlur()}
/>;