【问题标题】:how can i change background after 1 second in react native?如何在反应原生 1 秒后更改背景?
【发布时间】:2021-06-14 21:07:02
【问题描述】:

我想要做的是框内的背景颜色保持着色 0.5 秒然后消失。比如当你点击YouTube评论警报时,框内的背景颜色消失了。

第一次渲染时

有背景色

0.5秒后背景色就这样消失了

这是我的代码

    const Container = styled.View`
    border-bottom-color: lightblue;
    `;
    const CommentContainer = styled.View`
    `;

    const SecondCommentCon = styled.View`
    `;

    const UnserName = styled.Text`
    `;
    const Label = styled.Text`
    `;

    const TodoList = ({}) => {

      return (

      <Container>
      <CommentContainer>
      <SecondCommentCon>
      <UnserName>{yes?.[0]?.User?.nickname}</UnserName>
      <Label>{yes?.[0]?.content}</Label>
      </SecondCommentCon>
      </CommentContainer>
      </Container>

      )
      

我应该添加什么代码??

【问题讨论】:

标签: javascript css reactjs react-native styled-components


【解决方案1】:

您可以使用setTimeout() 在指定时间后将元素的背景颜色更改为className

首先,在 CSS 文件中定义一个类,使用您希望元素挂载的背景颜色

.bg-onmount {
  background-color: aquamarine;
}

确保您导入此文件(例如import "./App.css")。

然后你用你定义的类名的初始值声明一个状态变量

// a state variable for the background class
const [backgroundClass, setBackgroundClass] = useState("bg-onmount");

此状态值稍后将绑定到元素的className 属性。

在您的useEffect() 中,您可以将计时器设置为您希望它成为该颜色的时间,在您的情况下为 500 毫秒。在那之后,状态值将更新为我们设置为""的新className,因此背景颜色消失,组件重新渲染。

useEffect(() => {
  // set a timer
  const timer = setTimeout(() => {
    setBackgroundClass(""); // set class to none
  }, 500);

  // don't forget to clear in cleanup
  return () => {
    clearTimeout(timer);
  };
}, []);

不要忘记在你的清理函数中调用clearTimeout(),这将在组件卸载时停止计时器。

这就是你将这个值绑定到你的元素的方式

return (
  <div className={backgroundClass}>
    <p>Some text here</p>
  </div>
);

this sandbox试试吧

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多