Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - How can I pass a prop to onBlur() and use a predefined function at the same time (React Native)?

I have a Text Input component that change its background color using onBlur and onFocus events. What I want to do is to pass another function to onBlur using props, so the component would perform both actions.

This is my component:

const Input: React.FC<TextInputProps> = (props) => {
    const [color, setColor] = useState("#f2f2f2");

    return (
        <TextInput
            onFocus={() => setColor('#f9ffc4')}
            onBlur={() => setColor('#f2f2f2')} // I would like to use props.onBlur here in addition to setColor()
            onChangeText={props.onChangeText}
            style={{ backgroundColor: color }}
            value={props.value}
        >
        </TextInput>
    )
}

export default Input; 

And this is how I use it:

return (
    <Input
        onChangeText={ handleChange('cpf') }
        value={values.cpf}
        onBlur={() => setFieldTouched('cpf')} //I want to call it along with the method declared in the component
    />
    {touched.cpf && errors.cpf &&
        <Text style={{ color: 'red', width: '100%', textAlign: 'right' }}>{errors.cpf} </Text>
    }
)

I know that I could use setColor() here, but I have lots of other inputs and if I did that, I would have to create an useState const for each one of them, and that's not what I want.

If someone could help me here I would really appreciate it, and if something is not clear in my question, just ask me and I will try to explain better.

question from:https://stackoverflow.com/questions/65889482/how-can-i-pass-a-prop-to-onblur-and-use-a-predefined-function-at-the-same-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
onBlur={() => {
  setColor('#f2f2f2');
  props.onBlur();
}}

Is this what you want?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...