React Native 为什么我的文本输入样式在重新渲染时不更新?

rur96b6h  于 2023-04-22  发布在  React
关注(0)|答案(1)|浏览(118)

我想在文本输入被聚焦时应用特殊的样式。我试图通过将focused声明为组件状态并在聚焦/模糊时重新渲染来实现此行为。但是,它并没有像预期的那样工作。

import React from "react";
import { useState } from "react";
import { Text, View, TextInput } from "react-native";

function App() {
  console.log("rendering...");

  const [focused, setFocused] = useState(false);

  const inputStyles = [
    {
      maxWidth: 100,
      borderColor: "black",
      borderWidth: 1
    },
    focused && { borderColor: "red" }
  ];

  const handleFocus = () => {
    console.log("focusing");
    setFocused(true);
  };

  const handleBlur = () => {
    console.log("unfocusing");
    setFocused(false);
  };

  return (
    <View style={{ paddingTop: 10, paddingLeft: 10 }}>
      <Text style={{ marginBottom: 8 }}>Type something below</Text>
      <TextInput
        value="Hello"
        style={inputStyles}
        onFocus={handleFocus}
        onBlur={handleBlur}
      ></TextInput>
    </View>
  );
}

export default App;

我可以在控制台上看到handleFocushandleBlur被正确调用。我可以看到组件也被重新渲染。但是,红色边框没有应用。我在这里错过了什么?
代码可在代码沙箱上快速复制:https://codesandbox.io/s/vigorous-mclaren-b0lwgl?file=/src/App.js

bttbmeg0

bttbmeg01#

问题是轮廓出现在输入的上方。将轮廓设置为"none"会使边框颜色按照我想要的变化。
最终版本:

import React from "react";
import { useState } from "react";
import { Text, View, TextInput } from "react-native";

function App() {
  console.log("rendering...");

  const [focused, setFocused] = useState(false);

  const inputStyles = [{
    maxWidth: 100,
    borderColor: "black",
    borderWidth: 1,
    outline: 'none'},
    focused && { borderColor: 'red'}
  ]

  const handleFocus = () => {
    console.log("focusing");
    setFocused(true);
  };

  const handleBlur = () => {
    console.log("unfocusing");
    setFocused(false);
  };

  return (
    <View style={{ paddingTop: 10, paddingLeft: 10 }}>
      <Text style={{ marginBottom: 8 }}>Type something below</Text>
      <TextInput
        value="Hello"
        style={inputStyles}
        onFocus={handleFocus}
        onBlur={handleBlur}
      ></TextInput>
    </View>
  );
}

export default App;

相关问题