首页 > 解决方案 > 无法从 ref setNativeProps 更改文本样式

问题描述

当我的一些 textInput 成为焦点时,我想改变我的组件的一些样式,

我使用世博会 34.0.0

有两种方法,我尝试过:使用 ref 和使用状态,两者都有我需要了解的问题。

到目前为止,当我通过TextInput 的函数<TextInput>更改它们时,样式按预期工作。onFocus

但是当我尝试<Text>通过包含或使用按钮refTitle通过调用以相同的方法进行更改来更改样式时refTitle.current.setNativeProps()不起作用,每次我尝试更改 Text 样式时,它只会返回 refTitle.current.setNativeProps 未定义。

const refTitle = useRef(null)
const refUser = useRef(null)

return (
    <Card>
        <Margin>
            <Text ref={ refTitle } style={ styles.title }>as</Text>
            <TextInput
                ref={ refUser }
                style={ [styles.input] }
                onSubmitEditing={ () => refPassword.current.focus() }
                onFocus={ () => refUser.current.setNativeProps({ style: { borderColor: FOCUS_COLOR } }) }
                onBlur={ () => refUser.current.setNativeProps({ style: { borderColor: BLUR_COLOR } }) }
            />

所以如果我改变 textInput 中的 onFocus

const handleFocus = () => {
        refTitle.current.setNativeProps({ style: { color: FOCUS_COLOR } })
        refUser.current.setNativeProps({ style: { borderColor: FOCUS_COLOR } })
    }

我不知道为什么它不起作用,一直在搜索但指南告诉我没关系,这是最近 React Native 中的错误吗?

第二。我确实使用了状态,这更简单,但有一种我不明白的错误。

我只是使用 onFocus 函数来设置新颜色,...每次单击 textInput 时,它都会改变颜色...但它并没有真正聚焦,我必须再次单击以使其完全聚焦(键盘显示和指示器开始滴答作响)

标签: javascriptreact-nativedomreact-hooksref

解决方案


您必须使用参考才能使用 setNativeProps

 <TextInput
 ref={ref => {this.referencedeTF = ref;
          }}
/>
  this.referencedeTF.setNativeProps({
        borderColor: "red",
        borderWidth: 1
      });

您使用参考错误的方式。


推荐阅读