简体   繁体   English

如何在数组中使用状态钩子

[英]How to useState hooks with array

I am not able to push the number index in the array of useState.我无法推送 useState 数组中的数字索引。 Where I am going wrong, do I want to push the index of numbers when I click them?我哪里出错了,我想在单击它们时推送数字索引吗? I am extracting the previous state array and then I push new but nothing happens.我正在提取以前的状态数组,然后推送新的但没有任何反应。 How to push a new element inside useState array React hook?如何在 useState 数组 React 钩子中推送新元素? My code doesn't work!!我的代码不起作用!! Please someone check.请有人检查。

Game.js游戏.js

import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import RandomNumber from "./RandomNumber";

export default function Game(props) {
  const [state, setstate] = useState([]);
  let randomNumber = Array.from({ length: props.randomNumberCount }).map(
    () => 1 + Math.floor(10 * Math.random())
  );
  let target = randomNumber
    .slice(0, props.randomNumberCount - 2)
    .reduce((acc, curr) => acc + curr, 0);
  const isNumberSelected = (numberIndex) => {
    return state.indexOf(numberIndex) >= 0;
  };
  const selectNumber = (numberIndex) => {
    setstate((arr) => [...arr, numberIndex]);
  };
  return (
    <View style={styles.container}>
      <Text style={styles.header}>Target Sum Game</Text>
      <Text style={styles.target}>{target}</Text>
      <View style={styles.randomContainer}>
        {randomNumber.map((randomNumber, index) => (
          <RandomNumber
            key={index}
            id={index}
            number={randomNumber}
            isSelected={isNumberSelected(index)}
            onClick={() => selectNumber}
          />
        ))}
      </View>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ddd",
    paddingTop: 30,
  },
  target: {
    fontSize: 30,
    backgroundColor: "#aaa",
    margin: 50,
    marginHorizontal: 70,
    textAlign: "center",
  },
  header: {
    fontSize: 35,
    backgroundColor: "dodgerblue",
    textAlign: "center",
    marginHorizontal: 30,
    marginTop: 50,
  },
  randomContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-around",
  },
});

RandomNumber.js随机数.js

import React from "react";
import { StyleSheet, Text, TouchableOpacity } from "react-native";

export default function RandomNumber(props) {
  const handlePress = () => {
    props.onClick(props.id);
  };
  return (
    <TouchableOpacity onPress={handlePress()}>
      <Text style={[styles.random, props.isSelected && styles.selected]}>
        {props.number}
      </Text>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  random: {
    backgroundColor: "#999",
    width: 100,
    marginHorizontal: 35,
    marginVertical: 25,
    fontSize: 35,
    textAlign: "center",
  },
  selected: {
    opacity: 0.3,
  },
});

You need to change the onClick prop and pass the randomNumber (or index depending of what you want to do) to the selectNumber function:您需要更改 onClick 道具并将 randomNumber (或索引取决于您想要做什么)传递给 selectNumber 函数:

// Not sure if you want to pass randonNumber or index but you get the idea
onClick={() => selectNumber(randomNumber)}

你不是在调用函数

onClick={() => selectNumber(index)}
<TouchableOpacity onPress={handlePress()}>

should be应该

<TouchableOpacity onPress={()=>handlePress()}>

and

() => selectNumber

should be应该

() => selectNumber()

please try it请尝试一下

Might Be This Helpful:可能有帮助:

Home.Js主页.Js

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import RandomNumber from './RandomNumber';

const Home = props => {
  const [state, setstate] = useState([]);

  useEffect(() => {
    console.log('state', state);
  }, [state]);

  let randomNumber = Array.from({length: 10}).map(
    () => 1 + Math.floor(10 * Math.random()),
  );

  let target = randomNumber
    .slice(0, props.randomNumberCount - 2)
    .reduce((acc, curr) => acc + curr, 0);

  const isNumberSelected = numberIndex => {
    return state.indexOf(numberIndex) >= 0;
  };

  const selectNumber = numberIndex => {
    console.log('numberIndex', numberIndex);
    setstate(arr => [...arr, numberIndex]);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.header}>Target Sum Game</Text>
      <Text style={styles.target}>{target}</Text>
      <View style={styles.randomContainer}>
        {randomNumber.map((randomNumber, index) => {
          return (
            <RandomNumber
              key={index}
              id={index}
              number={randomNumber}
              isSelected={isNumberSelected(index)}
              onClick={() => selectNumber(randomNumber)}
            />
          );
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ddd',
    paddingTop: 30,
  },
  target: {
    fontSize: 30,
    backgroundColor: '#aaa',
    margin: 50,
    marginHorizontal: 70,
    textAlign: 'center',
  },
  header: {
    fontSize: 35,
    backgroundColor: 'dodgerblue',
    textAlign: 'center',
    marginHorizontal: 30,
    marginTop: 50,
  },
  randomContainer: {},
});

export default Home;

RandomNumber.js随机数.js

import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';

export default function RandomNumber(props) {
  const handlePress = () => {
    props.onClick(props.id);
  };
  return (
    <View style={{}}>
      <TouchableOpacity onPress={() => handlePress()}>
        <Text style={[styles.random, props.isSelected && styles.selected]}>
          {props.number}
        </Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  random: {
    backgroundColor: '#999',
    width: 100,
    height: 100,
    marginHorizontal: 35,
    marginVertical: 25,
    fontSize: 35,
    textAlign: 'center',
  },
  selected: {
    opacity: 0.3,
  },
});

Output Log:输出日志:

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM