簡體   English   中英

反應原生 - '未定義不是對象'?

[英]React native - 'undefined is not an object'?

好吧,離開這個答案React native - “this.setState is not a function”試圖為背景顏色設置動畫? 我只是想在 React Native 中循環淡化視圖的背景顏色。

export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
        'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
        'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
        'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
  });


  //Set states and hooks
  //To change state 'color' - setColor('#ff0000');
  const colors = ["#fff", "#ff0000", "#00ff00", "#0000ff", "#0077ff"];
  const [color, setColor] = useState("#fff");
  const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));
  const [time, setTime] = useState(0);
  //const t = colors[randNum(0, colors.length)];

  //random num, exclusive
  function randNum(min, max) {
    return Math.floor(min + Math.random() * (max - min));
  }

  useEffect(() => {
    setBackgroundColor(new Animated.Value(0));
  }, []); // this will be only called on initial mounting of component,
  // so you can change this as your requirement maybe move this in a function which will be called,
  // you can't directly call setState/useState in render otherwise it will go in a infinite loop.

  useEffect(() => {
    Animated.timing(backgroundColor, {
      toValue: 100,
      duration: 5000
    }).start();
  }, [backgroundColor]);

  var bgColor = this.state.color.interpolate({
    inputRange: [0, 300],
    outputRange: ["rgba(255, 0, 0, 1)", "rgba(0, 255, 0, 1)"]
  });

  useEffect(() => {
    const interval = setInterval(() => {
      //setTime(new Date().getMilliseconds());
      setColor("#ff0000");
    }, 36000);
    return () => clearInterval(interval);
  }, []);

有了這個,一切檢查除了var bgColor = this.state.color會產生錯誤

undefined 不是 object 評估..

我不明白為什么這是一個問題,因為我將顏色設置為useState('#fff')我想在樣式表中使用color作為backgroundColor

如何正確設置?

如果您的組件是 function,則不應使用this.state. ,但您必須直接調用 state 名稱。

在您的代碼中:

var bgColor = color.interpolate({...})

代替:

var bgColor = this.state.color.interpolate({...})

從反應文檔

讀 State

當我們想在 class 中顯示當前計數時,我們閱讀此.state.count:

<p>You clicked {this.state.count} times</p>

在 function 中,我們可以直接使用 count:

<p>You clicked {count} times</p>

這是一個示例,不要為動畫值創建 state,而是使用備忘錄對其進行一次初始化並使用時序 function 對其進行更新

零食: https://snack.expo.io/GwJtJUJA0

代碼:

export default function App() {
  const { value } = React.useMemo(
    () => ({
      value: new Animated.Value(0),
    }),
    []
  );

  React.useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(value, {
          toValue: 1,
          duration: 1000,
        }),
        Animated.timing(value, {
          toValue: 0,
          duration: 1000,
        })
      ])
    ).start();
  }, []);

  const backgroundColor = value.interpolate({
    inputRange: [0, 1],
    outputRange: ['#0dff4d', '#ff390d'],
  });

  return (
    <View style={styles.container}>
      <Animated.View style={{ width: 200, height: 100, backgroundColor }} />
    </View>
  );
}

在功能組件中,您無需使用 this.state.abc 訪問組件的 state 屬性/變量,而是直接使用this.state.abc變量的名稱。 所以你應該做的是:

    var bgColor = color.interpolate({
      inputRange: [0, 300],
      outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM