Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - Dynamically creating and handling multiple togglebuttons in Reactjs using Material-ui ToggleButtons

I am trying to create a sidebar that has a dynamic amount of toggle buttons created from an object(keys,values). I can't seem to get the "key" value to change the corresponding "value" in my state. I am using @material-ui/lab/ToggleButton as my button components and I can retrieve the value selected but I can't find the index or value that's being changed. I created a sandbox for people to see the exact issue I am working with. I've tried looking in the html attributes(and creating my own), but I still am not able to get it. Even a suggestion to try some other way would be appreciated, though I'd like to see I am able to get it done with what I have already. Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use inline function with a key param in the onClick handler:

import React, { useState } from "react";

import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";

export default function MultipleToggleSelection() {
  const mylist = {
    a: "1",
    b: "1",
    c: "1",
    d: "1"
  };

  const [oneTwoThree, setOneTwoThree] = useState(mylist);

  const handleToggle = (key, value) => {
    oneTwoThree[key] = value;
    setOneTwoThree({...oneTwoThree});
  };

  return (
    <div>
      <div>{JSON.stringify(oneTwoThree, null, ' ')}</div>

      <List>
        {Object.keys(oneTwoThree).map((key, index) => (
          <ListItem key={key}>
            <ToggleButtonGroup
              value={oneTwoThree[index]}
              exclusive
              onChange={(event, value) => handleToggle(key, value)}
            >
              <ToggleButton value="1">1</ToggleButton>
              <ToggleButton value="2">2</ToggleButton>
              <ToggleButton value="3">3</ToggleButton>
            </ToggleButtonGroup>
            {key}
          </ListItem>
        ))}
      </List>
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...