简体   繁体   中英

Converting string to function name

Learning React Native. Trying to convert a string into a function name. Getting an error saying "func is not a function. func is undefined". Need some help please. The end objective is to create a view with a background color and having buttons for increasing / decreasing RGB values

  const [red, setRed] = useState(0);
  const [green, setGreen] = useState(0);
  const [blue, setBlue] = useState(0);

  const setColor = (color, change) => {
    // color === "red", "green", "blue"
    // change === +10, -10
    const colorCapitalized = color.charAt(0).toUpperCase() + color.slice(1);
    var stateMethod = 'set' + colorCapitalized;
    var func = window[stateMethod];

    if (color + change > 255 || color + change < 0) {
      return;
    } else {
      func(color + change);
    }
  };

Avoid using the window object (or globals in general). You certainly can't use it with local variables like your setRed and such.

If you really want to do it that way, put the functions on an object:

const setters = {
    red: setRed,
    green: setGreen,
    blue: setBlue
};

then use color to index into it:

const setter = setters[color];
setter(color + change);

or even

setters[color](color + change);

You can also do the same with the values. Then your setColor gets much simpler (particularly if we only do the math once and reuse the result):

const [red, setRed] = useState(0);
const [green, setGreen] = useState(0);
const [blue, setBlue] = useState(0);
const setters = {
    red: setRed,
    green: setGreen,
    blue: setBlue
};
const values = {
    red,
    green,
    blue
};

const setColor = (color, change) => {
  const update = values[color] + change;
  if (update >= 0 && update <= 255) {
    setters[color](update);
  }
};

That said , it seems odd to need setColor . You might consider looking at whether you really need that, possibly even posting a new question ( not an update to this question) with the full context for why you think you need it, asking whether you can avoid setColor .

How about wrapping the setters

// do you really need the `color` arg?
const clamped = ([value, setter]) => [value, (color, change) => {
  let w = value + change;
  if(w >= 0 && w < 255) setter(value = w);
}];

const [red, setRed] = clamped(useState(0));
const [green, setGreen] = clamped(useState(0));
const [blue, setBlue] = clamped(useState(0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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