【问题标题】:How can I pass a prop to onBlur() and use a predefined function at the same time (React Native)?如何将道具传递给 onBlur() 并同时使用预定义的函数(React Native)?
【发布时间】:2021-04-29 12:52:46
【问题描述】:

我有一个文本输入组件,它使用 onBlur 和 onFocus 事件更改其背景颜色。我想要做的是使用 props 将另一个函数传递给 onBlur,因此组件将执行这两个操作。

这是我的组件:

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; 

这就是我使用它的方式:

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>
    }
)

我知道我可以在这里使用 setColor(),但我还有很多其他输入,如果我这样做了,我将不得不为每个输入创建一个 useState const,这不是我想要的。

如果有人可以在这里帮助我,我将不胜感激,如果我的问题不清楚,请问我,我会尽力解释得更好。

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:
    onBlur={() => {
      setColor('#f2f2f2');
      props.onBlur();
    }}
    

    这是你想要的吗?

    【讨论】:

    • 我已经尝试过这种方式,但是像这样只会发生setColor(),其他方法不会通过props传递,这让我很困惑。
    • 你的编辑和这个答案有区别,仔细看看
    • props.onBlur(); 不是 props.onBlur
    • @ArifArifi @konstantin 很抱歉我没有引起注意,props.onBlur() 在 vscode 上给了我这个错误:Expected 1 arguments, but got 0. An argument for 'e' was not provided. 所以我认为它不起作用,但是确实如此。显示这个错误,我可以保持这样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2018-08-25
    • 2021-04-23
    • 2020-07-17
    • 2021-05-26
    • 2023-03-28
    相关资源
    最近更新 更多